<!DOCTYPE html>
<html lang="en" dir="ltr">

<head prefix="og: http://ogp.me/ns#">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>libpcap、tcpdump以及kernel/net的部分源码阅读 – ruokeqx&#39;s blog</title>
    


  
  <script defer src="/js/fuse.min.8dfbf8696f107ab8b55732efbb04c5c51576692a4a2cce6effef9f6e92d341a7.js"></script>



<script src="/js/enquire.min.aa37bdcb743826eecdae5c5d177fc7d6552340f1b4378ffaa9c82b2c6111400b.js"></script>

<script defer src="/js/lazysizes.min.498676c34eb225e85357ab0ce19c3c1244f3bd0bf595e5684d1b9d50ea4fbc42.js"></script>

<script defer src="/js/helper/getParents.min.b75dda22e2d1c0e1e0574c7764bb95bec70c0fb0d4d5440339ba68c685d5a661.js"></script>

<script defer src="/js/helper/fadeinout.min.b1a8c6db3f3cc261756044570d21596f0f083625d41433dc9ac02aba5e53777b.js"></script>

<script defer src="/js/helper/closest.min.js"></script>
  
<script>
  "use strict";

  
  
  if (window.NodeList && !NodeList.prototype.forEach) {
    NodeList.prototype.forEach = Array.prototype.forEach;
  }

  
  if (!String.prototype.includes) {
    String.prototype.includes = function (search, start) {
      'use strict';

      if (search instanceof RegExp) {
        throw TypeError('first argument must not be a RegExp');
      }
      if (start === undefined) { start = 0; }
      return this.indexOf(search, start) !== -1;
    };
  }

  
  Document.prototype.append = Element.prototype.append = function append() {
    this.appendChild(_mutation(arguments));
  };
  function _mutation(nodes) {
    if (!nodes.length) {
      throw new Error('DOM Exception 8');
    } else if (nodes.length === 1) {
      return typeof nodes[0] === 'string' ? document.createTextNode(nodes[0]) : nodes[0];
    } else {
      var
      fragment = document.createDocumentFragment(),
      length = nodes.length,
      index = -1,
      node;

      while (++index < length) {
        node = nodes[index];

        fragment.appendChild(typeof node === 'string' ? document.createTextNode(node) : node);
      }

      return fragment;
    }
  }

  
  if (!String.prototype.startsWith) {
    String.prototype.startsWith = function (searchString, position) {
      position = position || 0;
      return this.indexOf(searchString, position) === position;
    };
  }
  


  document.addEventListener('DOMContentLoaded', function () {
    
    var navCollapseBtn = document.querySelector('.navbar__burger');
    navCollapseBtn ? navCollapseBtn.addEventListener('click', function (e) {
      var navCollapse = document.querySelector('.navbarm__collapse');

      if (navCollapse) {
        var dataOpen = navCollapse.getAttribute('data-open');

        if (dataOpen === 'true') {
          navCollapse.setAttribute('data-open', 'false');
          navCollapse.style.maxHeight = 0;
          navCollapseBtn.classList.remove('is-active');
        } else {
          navCollapse.setAttribute('data-open', 'true');
          navCollapse.style.maxHeight = navCollapse.scrollHeight + "px";
          navCollapseBtn.classList.add('is-active');
        }
      }
    }) : null;
    


    
    var tables = document.querySelectorAll('.single__contents > table');
    for (let i = 0; i < tables.length; i++) {
      var table = tables[i];
      var wrapper = document.createElement('div');
      wrapper.className = 'table-wrapper';
      table.parentElement.replaceChild(wrapper, table);
      wrapper.appendChild(table);
    }
    


    
    var footNoteRefs = document.querySelectorAll('.footnote-ref');
    var footNoteBackRefs = document.querySelectorAll('.footnote-backref');

    footNoteRefs ? 
    footNoteRefs.forEach(function(elem, idx) {
      elem.onmouseenter = function () {
        if (navbar.classList.contains('scrolling')) {
          navbar.classList.remove('scrolling');
        }
      }

      elem.onmouseleave = function () {
        if (!navbar.classList.contains('scrolling')) {
          setTimeout(function () {
            navbar.classList.add('scrolling');
          }, 100);
        }
      }

      elem.onclick = function () {
        if (!navbar.classList.contains('scrolling')) {
          navbar.classList.remove('navbar--show');
          navbar.classList.remove('navbar--hide');
          navbar.classList.add('navbar--hide');
        }
      }
    }) : null;

    footNoteBackRefs ? 
    footNoteBackRefs.forEach(function(elem, idx) {
      elem.onmouseenter = function () {
        if (navbar.classList.contains('scrolling')) {
          navbar.classList.remove('scrolling');
        }
      }

      elem.onmouseleave = function () {
        if (!navbar.classList.contains('scrolling')) {
          setTimeout(function() {
            navbar.classList.add('scrolling');
          }, 100);
        }
      }

      elem.onclick = function () {
        if (!navbar.classList.contains('scrolling')) {
          navbar.classList.remove('navbar--show');
          navbar.classList.remove('navbar--hide');
          navbar.classList.add('navbar--hide');
        }
      }
    }) : null;
    


    
    var summaryContainer = document.querySelector('.summary__container');
    var searchResult = document.querySelector('.search-result');
    var searchResultCloseBtn = document.querySelector('.search-result__close');
    searchResultCloseBtn ? searchResultCloseBtn.addEventListener('click', function (e) {
      searchResult.setAttribute('data-display', 'none');
      summaryContainer.setAttribute('data-display', 'block');
    }) : null;
    


    
    document.querySelectorAll('.tab') ? 
    document.querySelectorAll('.tab').forEach(function(elem, idx) {
      var containerId = elem.getAttribute('id');
      var containerElem = elem;
      var tabLinks = elem.querySelectorAll('.tab__link');
      var tabContents = elem.querySelectorAll('.tab__content');
      var ids = [];

      tabLinks && tabLinks.length > 0 ?
      tabLinks.forEach(function(link, index, self) {
        link.onclick = function(e) {
          for (var i = 0; i < self.length; i++) {
            if (index === parseInt(i, 10)) {
              if (!self[i].classList.contains('active')) {
                self[i].classList.add('active');
                tabContents[i].style.display = 'block';
              }
            } else {
              self[i].classList.remove('active');
              tabContents[i].style.display = 'none';
            }
          }
        }
      }) : null;
    }) : null;
    


    
    document.querySelectorAll('.codetab') ? 
    document.querySelectorAll('.codetab').forEach(function(elem, idx) {
      var containerId = elem.getAttribute('id');
      var containerElem = elem;
      var codetabLinks = elem.querySelectorAll('.codetab__link');
      var codetabContents = elem.querySelectorAll('.codetab__content');
      var ids = [];

      codetabLinks && codetabLinks.length > 0 ?
      codetabLinks.forEach(function(link, index, self) {
        link.onclick = function(e) {
          for (var i = 0; i < self.length; i++) {
            if (index === parseInt(i, 10)) {
              if (!self[i].classList.contains('active')) {
                self[i].classList.add('active');
                codetabContents[i].style.display = 'block';
              }
            } else {
              self[i].classList.remove('active');
              codetabContents[i].style.display = 'none';
            }
          }
        }
      }) : null;
    }) : null;
    


    
    var gttBtn = document.getElementById("gtt");
    gttBtn.style.display = "none";
    gttBtn.addEventListener('click', function () {
      if (window.document.documentMode) {
        document.documentElement.scrollTop = 0;
      } else {
        scrollToTop(250);
      }
    });

    function scrollToTop(scrollDuration) {
      var scrollStep = -window.scrollY / (scrollDuration / 15);
      var scrollInterval = setInterval(function () {
        if (window.scrollY != 0) {
          window.scrollBy(0, scrollStep);
        }
        else clearInterval(scrollInterval);
      }, 15);
    }

    var scrollFunction = function () {
      if (document.body.scrollTop > 250 || document.documentElement.scrollTop > 250) {
        gttBtn.style.display = "block";
      } else {
        gttBtn.style.display = "none";
      }
    }
    


    
    var expandBtn = document.querySelectorAll('.expand__button');

    for (let i = 0; i < expandBtn.length; i++) {
      expandBtn[i].addEventListener("click", function () {
        var content = this.nextElementSibling;
        if (content.style.maxHeight) {
          content.style.maxHeight = null;
          this.querySelector('svg').classList.add('expand-icon__right');
          this.querySelector('svg').classList.remove('expand-icon__down');
        } else {
          content.style.maxHeight = content.scrollHeight + "px";
          this.querySelector('svg').classList.remove('expand-icon__right');
          this.querySelector('svg').classList.add('expand-icon__down');
        }
      });
    }
    


    
    var lastScrollTop = window.pageYOffset || document.documentElement.scrollTop;
    var tocElem = document.querySelector('.toc');
    var tableOfContentsElem = tocElem ? tocElem.querySelector('#TableOfContents') : null;
    var toggleTocElem = document.getElementById('toggle-toc');
    var singleContentsElem = document.querySelector('.single__contents');
    var navbar = document.querySelector('.navbar');
    var tocFlexbox = document.querySelector('.toc__flexbox');
    var tocFlexboxOuter = document.querySelector('.toc__flexbox--outer');
    var expandContents = document.querySelectorAll('.expand__content');
    var boxContents = document.querySelectorAll('.box');
    var notAllowedTitleIds = null;

    
    var tocFolding = JSON.parse("true");
    
    var tocLevels = JSON.parse("[\"h2\",\"h3\",\"h4\",\"h5\"]");
    
    if (tocLevels) {
      tocLevels = tocLevels.toString();
    } else {
      tocLevels = "h1, h2, h3, h4, h5, h6";
    }

    
    singleContentsElem && singleContentsElem.querySelectorAll(".tab") ?
    singleContentsElem.querySelectorAll(".tab").forEach(function (elem) {
      elem.querySelectorAll(tocLevels).forEach(function (element) {
        notAllowedTitleIds = Array.isArray(notAllowedTitleIds) ?
          notAllowedTitleIds.concat(element.getAttribute('id')) :
          [element.getAttribute('id')];
      });
    }) : null;

    
    expandContents ? expandContents.forEach(function(elem) {
      elem.querySelectorAll(tocLevels).forEach(function (element) {
        notAllowedTitleIds = Array.isArray(notAllowedTitleIds) ?
          notAllowedTitleIds.concat(element.getAttribute('id')) :
          [element.getAttribute('id')];
      });
    }) : null;

    
    boxContents ? boxContents.forEach(function(elem) {
      elem.querySelectorAll(tocLevels).forEach(function (element) {
        notAllowedTitleIds = Array.isArray(notAllowedTitleIds) ?
          notAllowedTitleIds.concat(element.getAttribute('id')) :
          [element.getAttribute('id')];
      });
    }) : null;

    
    window.onscroll = function () {
      scrollFunction();
      
      var st = window.pageYOffset || document.documentElement.scrollTop;
      if (st > lastScrollTop) { 
        if (st < 250) {
          gttBtn.style.display = "none";
        } else {
          gttBtn.style.display = "block";
        }

        if (st < 45) {
          return null;
        }

        if (navbar.classList.contains('scrolling')) {
          if (!navbar.classList.contains('navbar--hide')) {
            navbar.classList.add('navbar--hide');
          } else if (navbar.classList.contains('navbar--show')) {
            navbar.classList.remove('navbar--show');
          }
        }

        if (singleContentsElem) {
          if (singleContentsElem.querySelectorAll(tocLevels).length > 0) {
            singleContentsElem.querySelectorAll(tocLevels).forEach(function (elem) {
              if (toggleTocElem && !toggleTocElem.checked) {
                return null;
              }

              if (notAllowedTitleIds && notAllowedTitleIds.includes(elem.getAttribute('id'))) {
                return null;
              }
              
              if (document.documentElement.scrollTop >= elem.offsetTop) {
                if (tableOfContentsElem) {
                  var id = elem.getAttribute('id');
                  tocElem.querySelectorAll('a').forEach(function (elem) {
                    elem.classList.remove('active');
                  });
                  tocElem.querySelector('a[href="#' + id + '"]') ?
                    tocElem.querySelector('a[href="#' + id + '"]').classList.add('active') : null;

                  if (false === tocFolding) {
                    
                  } else {
                    tableOfContentsElem.querySelectorAll('ul') ?
                      tableOfContentsElem.querySelectorAll('ul').forEach(function (rootUl) {
                        rootUl.querySelectorAll('li').forEach(function (liElem) {
                          liElem.querySelectorAll('ul').forEach(function (ulElem) {
                            ulElem.style.display = 'none';
                          });
                        });
                      }) : null;
                  }

                  var curElem = tableOfContentsElem.querySelector("[href='#" + id + "']");
                  if (curElem && curElem.nextElementSibling) {
                    curElem.nextElementSibling.style.display = 'block';
                  }
                  getParents(curElem, 'ul') ?
                    getParents(curElem, 'ul').forEach(function (elem) {
                      elem.style.display = 'block';
                    }) : null;
                }
              }
            });
          } else {
            if (tocFlexbox) {
              tocFlexbox.setAttribute('data-position', '');
              if (!tocFlexbox.classList.contains('hide')) {
                tocFlexbox.classList.add('hide');
              }
            }
            if (tocFlexboxOuter) {
              tocFlexboxOuter.setAttribute('data-position', '');
              if (!tocFlexboxOuter.classList.contains('hide')) {
                tocFlexboxOuter.classList.add('hide');
              }
            }
          }
        }
      } else { 
        if (st < 250) {
          gttBtn.style.display = "none";
        }

        if (navbar.classList.contains('scrolling')) {
          if (navbar.classList.contains('navbar--hide')) {
            navbar.classList.remove('navbar--hide');
          } else if (!navbar.classList.contains('navbar--show')) {
            navbar.classList.add('navbar--show');
          }
        }

        if (singleContentsElem) {
          if (singleContentsElem.querySelectorAll(tocLevels).length > 0) {
            singleContentsElem.querySelectorAll(tocLevels).forEach(function (elem) {
              if (toggleTocElem && !toggleTocElem.checked) {
                return null;
              }
              
              if (notAllowedTitleIds && notAllowedTitleIds.includes(elem.getAttribute('id'))) {
                return null;
              }

              if (document.documentElement.scrollTop >= elem.offsetTop) {
                if (tableOfContentsElem) {
                  var id = elem.getAttribute('id');
                  tocElem.querySelectorAll('a').forEach(function (elem) {
                    elem.classList.remove('active');
                  });
                  tocElem.querySelector('a[href="#' + id + '"]') ?
                    tocElem.querySelector('a[href="#' + id + '"]').classList.add('active') : null;

                  if (false === tocFolding) {
                    
                  } else {
                    tableOfContentsElem.querySelectorAll('ul') ?
                      tableOfContentsElem.querySelectorAll('ul').forEach(function (rootUl) {
                        rootUl.querySelectorAll('li').forEach(function (liElem) {
                          liElem.querySelectorAll('ul').forEach(function (ulElem) {
                            ulElem.style.display = 'none';
                          });
                        });
                      }) : null;
                  }

                  var curElem = tableOfContentsElem.querySelector("[href='#" + id + "']");
                  if (curElem && curElem.nextElementSibling) {
                    curElem.nextElementSibling.style.display = 'block';
                  }
                  getParents(curElem, 'ul') ?
                    getParents(curElem, 'ul').forEach(function (elem) {
                      elem.style.display = 'block';
                    }) : null;
                }
              }
            });
          } else {
            if (tocFlexbox && !tocFlexbox.classList.contains('hide')) {
              tocFlexbox.classList.add('hide');
            }
            if (tocFlexboxOuter && !tocFlexboxOuter.classList.contains('hide')) {
              tocFlexboxOuter.classList.add('hide');
            }
          }
          
        }

        if (tableOfContentsElem && document.documentElement.scrollTop < 250) {
          if (false === tocFolding) {

          } else {
            tableOfContentsElem.querySelector('ul') ?
              tableOfContentsElem.querySelector('ul').querySelectorAll('li').forEach(function (liElem) {
                liElem.querySelectorAll('ul').forEach(function (ulElem) {
                  ulElem.style.display = 'none';
                });
              }) : null;
          }
        }
      }
      lastScrollTop = st <= 0 ? 0 : st;
    };
  


  
    var localTheme = localStorage.getItem('theme');
    var rootEleme = document.getElementById('root');
    var selectThemeElem = document.querySelectorAll('.select-theme');
    var selectThemeItemElem = document.querySelectorAll('.select-theme__item');
    
    
    var skinDarkCode = JSON.parse("\"dark\"");
    
    var skinLightCode = JSON.parse("\"light\"");
    
    var skinHackerCode = JSON.parse("\"hacker\"");
    
    var skinSolarizedCode = JSON.parse("\"solarized\"");
    
    var skinKimbieCode = JSON.parse("\"kimbie\"");

    var setMetaColor = function(themeColor) {
      var metaMsapplicationTileColor = document.getElementsByName('msapplication-TileColor')[0];
      var metaThemeColor = document.getElementsByName('theme-color')[0];
      var metaMsapplicationNavbuttonColor = document.getElementsByName('msapplication-navbutton-color')[0];
      var metaAppleMobileWebAappStatusBarStyle = document.getElementsByName('apple-mobile-web-app-status-bar-style')[0];

      if (themeColor.includes('dark')) {
        metaMsapplicationTileColor.setAttribute('content', '#fcfcfa');
        metaThemeColor.setAttribute('content', '#403E41');
        metaMsapplicationNavbuttonColor.setAttribute('content', '#403E41');
        metaAppleMobileWebAappStatusBarStyle.setAttribute('content', '#403E41');
      } else if (themeColor.includes('light')) {
        metaMsapplicationTileColor.setAttribute('content', '#555');
        metaThemeColor.setAttribute('content', '#eee');
        metaMsapplicationNavbuttonColor.setAttribute('content', '#eee');
        metaAppleMobileWebAappStatusBarStyle.setAttribute('content', '#eee');
      } else if (themeColor.includes('hacker')) {
        metaMsapplicationTileColor.setAttribute('content', '#e3cd26');
        metaThemeColor.setAttribute('content', '#252526');
        metaMsapplicationNavbuttonColor.setAttribute('content', '#252526');
        metaAppleMobileWebAappStatusBarStyle.setAttribute('content', '#252526');
      } else if (themeColor.includes('solarized')) {
        metaMsapplicationTileColor.setAttribute('content', '#d3af86');
        metaThemeColor.setAttribute('content', '#51412c');
        metaMsapplicationNavbuttonColor.setAttribute('content', '#51412c');
        metaAppleMobileWebAappStatusBarStyle.setAttribute('content', '#51412c');
      } else if (themeColor.includes('kimbie')) {
        metaMsapplicationTileColor.setAttribute('content', '#586e75');
        metaThemeColor.setAttribute('content', '#eee8d5');
        metaMsapplicationNavbuttonColor.setAttribute('content', '#eee8d5');
        metaAppleMobileWebAappStatusBarStyle.setAttribute('content', '#eee8d5');
      }
    }

    var parseSkinCode = function(themeText) {
      if (themeText === skinDarkCode) {
        return 'dark';
      } else if (themeText === skinLightCode) {
        return 'light';
      } else if (themeText === skinHackerCode) {
        return 'hacker';
      } else if (themeText === skinSolarizedCode) {
        return 'solarized';
      } else if (themeText === skinKimbieCode) {
        return 'kimbie';
      }
    }
    
    if (localTheme) {
      selectThemeItemElem ? 
      selectThemeItemElem.forEach(function (elem) {
        if (elem.text.trim() === localTheme) {
          elem.classList.add('is-active');
        } else {
          elem.classList.remove('is-active');
        }
      }) : null;

      setMetaColor(localTheme);
    } else {
      setMetaColor(rootEleme.className);
    }

    selectThemeItemElem ? 
    selectThemeItemElem.forEach(function (v, i) {
      v.addEventListener('click', function (e) {
        var selectedThemeVariant = parseSkinCode(e.target.text.trim());
        localStorage.setItem('theme', selectedThemeVariant);
        setMetaColor(selectedThemeVariant);

        rootEleme.removeAttribute('class');
        rootEleme.classList.add('theme__' + selectedThemeVariant);
        selectThemeElem.forEach(function(rootElem) {
          rootElem.querySelectorAll('a').forEach(function (elem) {
            if (elem.classList) {
              if (elem.text.trim() === selectedThemeVariant) {
                if (!elem.classList.contains('is-active')) {
                  elem.classList.add('is-active');
                }
              } else {
                if (elem.classList.contains('is-active')) {
                  elem.classList.remove('is-active');
                }
              }
            }
          });
        });

        if (window.mermaid) {
          if (selectedThemeVariant === "dark" || selectedThemeVariant === "hacker") {
            mermaid.initialize({ theme: 'dark' });
            location.reload();
          } else {
            mermaid.initialize({ theme: 'default' });
            location.reload();
          }
        }

        var utterances = document.getElementById('utterances');
        if (utterances) {
          utterances.querySelector('iframe').contentWindow.postMessage({
            type: 'set-theme',
            theme: selectedThemeVariant === "dark" || selectedThemeVariant === "hacker" ? 'photon-dark' : selectedThemeVariant === 'kimbie' ? 'github-dark-orange' : 'github-light',
          }, 'https://utteranc.es');
        }

        var twitterCards = document.querySelectorAll('.twitter-timeline');
        if (twitterCards) {
          window.postMessage({
            type: 'set-twitter-theme',
            theme: selectedThemeVariant === 'light' || selectedThemeVariant === 'solarized' ? 'light' : 'dark',
          });
        }
      });
    }) : null;
  


  
    
    var baseurl = JSON.parse("\"https://ruokeqx.gitee.io\"");
    
    var permalink = JSON.parse("\"https://ruokeqx.gitee.io/posts/libpcaptcpdumpkernel-net%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB/\"");
    
    var langprefix = JSON.parse("\"\"");
    var searchResults = null;
    var searchMenu = null;
    var searchText = null;
    
    
    var enableSearch = JSON.parse("true");
    
    var searchDistance = JSON.parse("100");
    
    var searchThreshold = JSON.parse("0.4");
    
    var searchContent = JSON.parse("true");
    
    var enableSearchHighlight = JSON.parse("true");
    
    var searchResultPosition = JSON.parse("\"main\"");
    
    var sectionType = JSON.parse("\"posts\"");
    
    var kind = JSON.parse("\"page\"");
    
    var fuse = null;

    if (enableSearch) {
      (function initFuse() {
        var xhr = new XMLHttpRequest();
        if (sectionType === "publication" && kind !== "page") {
          xhr.open('GET', permalink + "index.json");
        } else {
          xhr.open('GET', baseurl + langprefix + "/index.json");
        }
        
        xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
        xhr.onload = function () {
          if (xhr.status === 200) {
            fuse = new Fuse(JSON.parse(xhr.response.toString('utf-8')), {
              keys: sectionType.includes('publication') ? ['title', 'abstract'] : 
                searchContent ? ['title', 'description', 'content'] : ['title', 'description'],
              includeMatches: enableSearchHighlight,
              shouldSort: true, 
              threshold: searchThreshold ? searchThreshold : 0.4, 
              location: 0, 
              distance: searchDistance ? searchDistance : 100, 
              maxPatternLength: 32,
              minMatchCharLength: 1,
              isCaseSensitive: false, 
              findAllMatches: false, 
              useExtendedSearch: false, 
            });
            window.fuse = fuse;
          }
          else {
            console.error('[' + xhr.status + ']Error:', xhr.statusText);
          }
        };
        xhr.send();
      })();
    }

    function makeLi(ulElem, obj) {
      var li = document.createElement('li');
      li.className = 'search-result__item';
      
      var a = document.createElement('a');
      a.innerHTML = obj.item.title;
      a.setAttribute('class', 'search-result__item--title');
      a.setAttribute('href', obj.item.uri);

      var descDiv = document.createElement('div');
      descDiv.setAttribute('class', 'search-result__item--desc');
      if (obj.item.description) {
        descDiv.innerHTML = obj.item.description;
      } else if (obj.item.content) {
        descDiv.innerHTML = obj.item.content.substring(0, 225);
      }
      
      li.appendChild(a);
      li.appendChild(descDiv);
      ulElem.appendChild(li);
    }

    function makeHighlightLi(ulElem, obj) {
      var li = document.createElement('li');
      li.className = 'search-result__item';
      var descDiv = null;

      var a = document.createElement('a');
      a.innerHTML = obj.item.title;
      a.setAttribute('class', 'search-result__item--title');
      a.setAttribute('href', obj.item.uri);

      if (obj.matches && obj.matches.length) {
        for (var i = 0; i < obj.matches.length; i++) {
          if ('title' === obj.matches[i].key) {
            a = document.createElement('a');
            a.innerHTML = generateHighlightedText(obj.matches[i].value, obj.matches[i].indices);
            a.setAttribute('class', 'search-result__item--title');
            a.setAttribute('href', obj.item.uri);
          }
          
          if ('description' === obj.matches[i].key) {
            descDiv = document.createElement('div');
            descDiv.setAttribute('class', 'search-result__item--desc');
            descDiv.innerHTML = generateHighlightedText(obj.item.description, obj.matches[i].indices);
          } else if ('content' === obj.matches[i].key) {
            if (!descDiv) {
              descDiv = document.createElement('div');
              descDiv.setAttribute('class', 'search-result__item--desc');
              descDiv.innerHTML = generateHighlightedText(obj.item.content.substring(0, 150), obj.matches[i].indices);
            }
          } else {
            if (obj.item.description) {
              descDiv = document.createElement('div');
              descDiv.setAttribute('class', 'search-result__item--desc');
              descDiv.innerHTML = obj.item.description;
            } else {
              descDiv = document.createElement('div');
              descDiv.setAttribute('class', 'search-result__item--desc');
              descDiv.innerHTML = obj.item.content.substring(0, 150);
            }
          }
        }

        li.appendChild(a);
        if (descDiv) {
          li.appendChild(descDiv);
        }
        if (li) {
          ulElem.appendChild(li);
        }
      }
    }

    function renderSearchResultsSide(searchText, results) {
      searchResults = document.getElementById('search-results');
      searchMenu = document.getElementById('search-menu');
      searchResults.setAttribute('class', 'dropdown is-active');
      
      var ul = document.createElement('ul');
      ul.setAttribute('class', 'dropdown-content search-content');

      if (results.length) {
        results.forEach(function (result) {
          var li = document.createElement('li');
          var a = document.createElement('a');
          a.setAttribute('href', result.uri);
          a.setAttribute('class', 'dropdown-item');
          a.appendChild(li);

          var titleDiv = document.createElement('div');
          titleDiv.innerHTML = result.title;
          titleDiv.setAttribute('class', 'menu-item__title');

          var descDiv = document.createElement('div');
          descDiv.setAttribute('class', 'menu-item__desc');
          if (result.description) {
            descDiv.innerHTML = result.description;
          } else if (result.content) {
            descDiv.innerHTML = result.content.substring(0, 150);
          }

          li.appendChild(titleDiv);
          li.appendChild(descDiv);
          ul.appendChild(a);
        });
      } else {
        var li = document.createElement('li');
        li.setAttribute('class', 'dropdown-item');
        li.innerText = 'No results found';
        ul.appendChild(li);
      }

      while (searchMenu.hasChildNodes()) {
        searchMenu.removeChild(
          searchMenu.lastChild
        );
      }
      
      searchMenu.appendChild(ul);
    }

    function renderSearchHighlightResultsSide(searchText, results) {
      searchResults = document.getElementById('search-results');
      searchMenu = document.getElementById('search-menu');
      searchResults.setAttribute('class', 'dropdown is-active');

      var ul = document.createElement('ul');
      ul.setAttribute('class', 'dropdown-content search-content');

      if (results.length) {
        results.forEach(function (result) {
          var li = document.createElement('li');
          var a = document.createElement('a');
          var descDiv = null;

          a.setAttribute('href', result.item.uri);
          a.setAttribute('class', 'dropdown-item');
          a.appendChild(li);

          var titleDiv = document.createElement('div');
          titleDiv.innerHTML = result.item.title;
          titleDiv.setAttribute('class', 'menu-item__title');
          
          if (result.matches && result.matches.length) {
            for (var i = 0; i < result.matches.length; i++) {
              if ('title' === result.matches[i].key) {
                titleDiv.innerHTML = generateHighlightedText(result.matches[i].value, result.matches[i].indices);
              }

              if ('description' === result.matches[i].key) {
                descDiv = document.createElement('div');
                descDiv.setAttribute('class', 'menu-item__desc');
                descDiv.innerHTML = generateHighlightedText(result.item.description, result.matches[i].indices);
              } else if ('content' === result.matches[i].key) {
                if (!descDiv) {
                  descDiv = document.createElement('div');
                  descDiv.setAttribute('class', 'menu-item__desc');
                  descDiv.innerHTML = generateHighlightedText(result.item.content.substring(0, 150), result.matches[i].indices);
                }
              } else {
                if (result.item.description) {
                  descDiv = document.createElement('div');
                  descDiv.setAttribute('class', 'menu-item__desc');
                  descDiv.innerHTML = result.item.description;
                } else {
                  descDiv = document.createElement('div');
                  descDiv.setAttribute('class', 'menu-item__desc');
                  descDiv.innerHTML = result.item.content.substring(0, 150);
                }
              }
            }
            
            li.appendChild(titleDiv);
            if (descDiv) {
              li.appendChild(descDiv);
            }
            ul.appendChild(a);
          }
        });
      } else {
        var li = document.createElement('li');
        li.setAttribute('class', 'dropdown-item');
        li.innerText = 'No results found';
        ul.appendChild(li);
      }

      while (searchMenu.hasChildNodes()) {
        searchMenu.removeChild(
          searchMenu.lastChild
        );
      }
      searchMenu.appendChild(ul);
    }

    function renderSearchResultsMobile(searchText, results) {
      searchResults = document.getElementById('search-mobile-results');

      var content = document.createElement('div');
      content.setAttribute('class', 'mobile-search__content');

      if (results.length > 0) {
        results.forEach(function (result) {
          var item = document.createElement('a');
          item.setAttribute('href', result.uri);
          item.innerHTML = '<div class="mobile-search__item"><div class="mobile-search__item--title">📄 ' + result.title + '</div><div class="mobile-search__item--desc">' + (result.description ? result.description : result.content) + '</div></div>';
          content.appendChild(item);
        });
      } else {
        var item = document.createElement('span');
        content.appendChild(item);
      }

      let wrap = document.getElementById('search-mobile-results');
      while (wrap.firstChild) {
        wrap.removeChild(wrap.firstChild)
      }
      searchResults.appendChild(content);      
    }

    function renderSearchHighlightResultsMobile(searchText, results) {
      searchResults = document.getElementById('search-mobile-results');

      var ul = document.createElement('div');
      ul.setAttribute('class', 'mobile-search__content');

      if (results.length) {
        results.forEach(function (result) {
          var li = document.createElement('li');
          var a = document.createElement('a');
          var descDiv = null;

          a.setAttribute('href', result.item.uri);
          a.appendChild(li);
          li.setAttribute('class', 'mobile-search__item');

          var titleDiv = document.createElement('div');
          titleDiv.innerHTML = result.item.title;
          titleDiv.setAttribute('class', 'mobile-search__item--title');
          
          if (result.matches && result.matches.length) {
            for (var i = 0; i < result.matches.length; i++) {
              if ('title' === result.matches[i].key) {
                titleDiv.innerHTML = generateHighlightedText(result.matches[i].value, result.matches[i].indices);
              }

              if ('description' === result.matches[i].key) {
                descDiv = document.createElement('div');
                descDiv.setAttribute('class', 'mobile-search__item--desc');
                descDiv.innerHTML = generateHighlightedText(result.item.description, result.matches[i].indices);
              } else if ('content' === result.matches[i].key) {
                if (!descDiv) {
                  descDiv = document.createElement('div');
                  descDiv.setAttribute('class', 'mobile-search__item--desc');
                  descDiv.innerHTML = generateHighlightedText(result.item.content.substring(0, 150), result.matches[i].indices);
                }
              } else {
                if (result.item.description) {
                  descDiv = document.createElement('div');
                  descDiv.setAttribute('class', 'mobile-search__item--desc');
                  descDiv.innerHTML = result.item.description;
                } else {
                  descDiv = document.createElement('div');
                  descDiv.setAttribute('class', 'mobile-search__item--desc');
                  descDiv.innerHTML = result.item.content.substring(0, 150);
                }
              }
            }
            
            li.appendChild(titleDiv);
            if (descDiv) {
              li.appendChild(descDiv);
            }
            ul.appendChild(a);
          }
        });
      } else {
        var item = document.createElement('span');
        ul.appendChild(item);
      }

      let wrap = document.getElementById('search-mobile-results');
      while (wrap.firstChild) {
        wrap.removeChild(wrap.firstChild)
      }
      searchResults.appendChild(ul);
    }

    function generateHighlightedText(text, regions) {
      if (!regions) {
        return text;
      }

      var content = '', nextUnhighlightedRegionStartingIndex = 0;

      regions.forEach(function(region) {
        if (region[0] === region[1]) {
          return null;
        }
        
        content += '' +
          text.substring(nextUnhighlightedRegionStartingIndex, region[0]) +
          '<span class="search__highlight">' +
            text.substring(region[0], region[1] + 1) +
          '</span>' +
        '';
        nextUnhighlightedRegionStartingIndex = region[1] + 1;
      });

      content += text.substring(nextUnhighlightedRegionStartingIndex);

      return content;
    };

    var searchElem = document.getElementById('search');
    var searchMobile = document.getElementById('search-mobile');
    var searchResultsContainer = document.getElementById('search-results');

    searchElem ?
    searchElem.addEventListener('input', function(e) {
      if (!e.target.value | window.innerWidth < 770) {
        searchResultsContainer ? searchResultsContainer.setAttribute('class', 'dropdown') : null;
        searchResult ? searchResult.setAttribute('data-display', 'none') : null;
        summaryContainer ? summaryContainer.setAttribute('data-display', 'block') : null;
        return null;
      }

      searchText = e.target.value;
      var results = fuse.search(e.target.value);
      
      if (searchResultPosition === "main") {
        if (enableSearchHighlight) {
          renderSearchHighlightResultsMain(searchText, results);
        } else {
          renderSearchResultsMain(searchText, results);
        }
      } else {
        if (enableSearchHighlight) {
          renderSearchHighlightResultsSide(searchText, results);
        } else {
          renderSearchResultsSide(searchText, results);
        }
        
        var dropdownItems = searchResultsContainer.querySelectorAll('.dropdown-item');
        dropdownItems ? dropdownItems.forEach(function(item) {
          item.addEventListener('mousedown', function(e) {
            e.target.click();
          });
        }) : null;
      }
    }) : null;

    searchElem ? 
    searchElem.addEventListener('blur', function() {
      if (window.innerWidth < 770) {
        return null;
      }
      searchResultsContainer ? searchResultsContainer.setAttribute('class', 'dropdown') : null;
    }) : null;

    searchElem ? 
    searchElem.addEventListener('click', function(e) {
      if (window.innerWidth < 770) {
        return null;
      }
      if (!e.target.value) {
        searchResultsContainer ? searchResultsContainer.setAttribute('class', 'dropdown') : null;
        return null;
      }

      searchText = e.target.value;
      var results = fuse.search(e.target.value);

      if (searchResultPosition === "main") {
        if (enableSearchHighlight) {
          renderSearchHighlightResultsMain(searchText, results);
        } else {
          renderSearchResultsMain(searchText, results);
        }
      } else{
        if (enableSearchHighlight) {
          renderSearchHighlightResultsSide(searchText, results);
        } else {
          renderSearchResultsSide(searchText, results);
        }

        var dropdownItems = searchResultsContainer.querySelectorAll('.dropdown-item');
        dropdownItems ? dropdownItems.forEach(function (item) {
          item.addEventListener('mousedown', function (e) {
            e.target.click();
          });
        }) : null;
      }
    }) : null;

    var searchMenuElem = document.getElementById("search-menu");
    var activeItem = document.querySelector('#search-menu .dropdown-item.is-active');
    var activeIndex = null;
    var items = null;
    var searchContainerMaxHeight = 350;

    searchElem ? 
    searchElem.addEventListener('keydown', function(e) {
      if (window.innerWidth < 770) {
        return null;
      }

      if (e.key === 'Escape') {
        searchResult ? searchResult.setAttribute('data-display', 'none') : null;
        summaryContainer ? summaryContainer.setAttribute('data-display', 'block') : null;
      }

      var items = document.querySelectorAll('#search-menu .dropdown-item');
      var keyCode = e.which || e.keyCode;

      if (!items || !items.length) {
        return null;
      }
      
      if (e.key === 'ArrowDown' || keyCode === 40) {
        if (activeIndex === null) {
          activeIndex = 0;
          items[activeIndex].classList.remove('is-active');
        } else {
          items[activeIndex].classList.remove('is-active');
          activeIndex = activeIndex === items.length - 1 ? 0 : activeIndex + 1;
        }
        items[activeIndex].classList.add('is-active');

        let overflowedPixel = items[activeIndex].offsetTop + items[activeIndex].clientHeight - searchContainerMaxHeight;
        if (overflowedPixel > 0) {
          document.querySelector(".search-content").scrollTop += items[activeIndex].getBoundingClientRect().height;
        } else if (activeIndex === 0) {
          document.querySelector(".search-content").scrollTop = 0;
        }
      } else if (e.key === 'ArrowUp' || keyCode === 38) {
        if (activeIndex === null) {
          activeIndex = items.length - 1;
          items[activeIndex].classList.remove('is-active');
        } else {
          items[activeIndex].classList.remove('is-active');
          activeIndex = activeIndex === 0 ? items.length - 1 : activeIndex - 1;
        }
        items[activeIndex].classList.add('is-active');
        
        let overflowedPixel = items[activeIndex].offsetTop + items[activeIndex].clientHeight - searchContainerMaxHeight;
        if (overflowedPixel < 0) {
          document.querySelector(".search-content").scrollTop -= items[activeIndex].getBoundingClientRect().height;
        } else {
          document.querySelector(".search-content").scrollTop = overflowedPixel + items[activeIndex].getBoundingClientRect().height;
        }
      } else if (e.key === 'Enter' || keyCode === 13) {
        if (items[activeIndex] && items[activeIndex].getAttribute('href')) {
          location.href = items[activeIndex].getAttribute('href');
        }
      } else if (e.key === 'Escape' || keyCode === 27) {
        e.target.value = null;
        if (searchResults) {
          searchResults.classList.remove('is-active');
        }
      }
    }) : null;

    searchMobile ? 
    searchMobile.addEventListener('input', function(e) {
      if (!e.target.value) {
        let wrap = document.getElementById('search-mobile-results');
        while (wrap.firstChild) {
          wrap.removeChild(wrap.firstChild);
        }
        return null;
      }

      searchText = e.target.value;
      var results = fuse.search(e.target.value);
      renderSearchResultsMobile(searchText, results);
      if (enableSearchHighlight) {
        renderSearchHighlightResultsMobile(searchText, results);
      } else {
        renderSearchResultsMobile(searchText, results);
      }
    }) : null;
  


  
    var mobileSearchInputElem = document.querySelector('#search-mobile');
    var mobileSearchClassElem = document.querySelector('.mobile-search');
    var mobileSearchBtnElems = document.querySelectorAll('.navbar-search');
    var mobileSearchCloseBtnElem = document.querySelector('#search-mobile-close');
    var mobileSearchContainer = document.querySelector('#search-mobile-container');
    var mobileSearchResultsElem = document.querySelector('#search-mobile-results');
    var htmlElem = document.querySelector('html');

    if (mobileSearchClassElem) {
      mobileSearchClassElem.style.display = 'none';
    }

    mobileSearchBtnElems ? 
    mobileSearchBtnElems.forEach(function (elem, idx) {
      elem.addEventListener('click', function () {
        if (mobileSearchContainer) {
          mobileSearchContainer.style.display = 'block';
        }

        if (mobileSearchInputElem) {
          mobileSearchInputElem.focus();
        }

        if (htmlElem) {
          htmlElem.style.overflowY = 'hidden';
        }
      });
    }) : null;

    mobileSearchCloseBtnElem ? 
    mobileSearchCloseBtnElem.addEventListener('click', function() {
      if (mobileSearchContainer) {
        mobileSearchContainer.style.display = 'none';
      }

      if (mobileSearchInputElem) {
        mobileSearchInputElem.value = '';
      }
      
      if (mobileSearchResultsElem) {
        while (mobileSearchResultsElem.firstChild) {
          mobileSearchResultsElem.removeChild(mobileSearchResultsElem.firstChild);
        }
      }

      if (htmlElem) {
        htmlElem.style.overflowY = 'visible';
      }
    }) : null;

    mobileSearchInputElem ?
    mobileSearchInputElem.addEventListener('keydown', function(e) {
      var keyCode = e.which || e.keyCode;
      if (e.key === 'Escape' || keyCode === 27) {
        if (mobileSearchContainer) {
          mobileSearchContainer.style.display = 'none';
        }
        
        if (mobileSearchInputElem) {
          mobileSearchInputElem.value = '';
        }

        if (mobileSearchResultsElem) {
          while (mobileSearchResultsElem.firstChild) {
            mobileSearchResultsElem.removeChild(mobileSearchResultsElem.firstChild);
          }
        }
        if (htmlElem) {
          htmlElem.style.overflowY = 'visible';
        }
      }
    }) : null;
  


  
    function renderSearchResultsMain(searchText, results) {
      var searchBody = document.querySelector('.search-result__body');
      var originUl = searchBody.querySelector('ul');
      var ul = document.createElement('ul');
      
      if (!searchText) {
        searchResult ? searchResult.setAttribute('data-display', 'none') : null;
        summaryContainer ? summaryContainer.setAttribute('data-display', 'block') : null;
      } else if (results) {
        if (results && results.length) {
          results.forEach(function (result) {
            makeLi(ul, result);
          });

          searchResult ? searchResult.setAttribute('data-display', 'block') : null;
          summaryContainer ? summaryContainer.setAttribute('data-display', 'none') : null;
        }
      }

      originUl.parentNode.replaceChild(ul, originUl);
    }

    function renderSearchHighlightResultsMain(searchText, results) {
      var searchBody = document.querySelector('.search-result__body');
      var originUl = searchBody.querySelector('ul');
      var ul = document.createElement('ul');

      if (!searchText) {
        searchResult ? searchResult.setAttribute('data-display', 'none') : null;
        summaryContainer ? summaryContainer.setAttribute('data-display', 'block') : null;
      } else if (results) {
        if (results && results.length) {
          results.forEach(function (result) {
            makeHighlightLi(ul, result);
          });

          searchResult ? searchResult.setAttribute('data-display', 'block') : null;
          summaryContainer ? summaryContainer.setAttribute('data-display', 'none') : null;
        }
      }

      originUl.parentNode.replaceChild(ul, originUl);
    }
  
  });
</script>
    
    


<link rel="stylesheet" href="/css/main.min.css">


    
<meta name="description" content="" />


<meta name="keywords" content="networking,kernel">

<meta name="created" content="2022-03-14T00:00:00&#43;0000">
<meta name="modified" content="2022-03-14T00:00:00&#43;0000">
<meta property="article:published_time" content="2022-03-14T00:00:00&#43;0000">

<meta name="author" content="ruokeqx">


<meta property="og:site_name" content="ruokeqx&#39;s blog">
<meta property="og:title" content="libpcap、tcpdump以及kernel/net的部分源码阅读">
<meta property="og:url" content="https://ruokeqx.gitee.io/posts/libpcaptcpdumpkernel-net%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB/">
<meta property="og:type" content="article">
<meta property="og:description" content="">

<meta name="generator" content="Hugo 0.100.2" />
<meta name="msapplication-TileColor" content="#fff">

<meta name="theme-color" content="#fff">

<meta name="msapplication-navbutton-color" content="#fff">

<meta name="apple-mobile-web-app-status-bar-style" content="#fff">

<link rel="canonical" href="https://ruokeqx.gitee.io/posts/libpcaptcpdumpkernel-net%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB/">

<link rel="manifest" href="/manifest.json">

  
  <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
  <link rel="icon" href="/favicon.png" sizes="any" type="image/png" />
  


    <script type="application/ld+json">
  {
    "@context": "https://schema.org",
    "@type": "WebPage",
    "headline": "libpcap、tcpdump以及kernel/net的部分源码阅读",
    "datePublished": "2022-03-14T00:00:00Z",
    "dateModified": "2022-03-14T00:00:00Z",
    "url" : "https://ruokeqx.gitee.io/posts/libpcaptcpdumpkernel-net%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB/",
    "description": "Begin 本文起因是操作系统课设任务新增系统调用，当时想法是新增一个网络抓包功能的系统调用，类似于简化版的tcpdump和kernel的缝合，所以就",
    "keywords": ["networking","kernel"],
    "mainEntityOfPage": {
      "@type": "WebPage",
      "@id": "https://ruokeqx.gitee.io"
    },
    "publisher": {
      "@type": "Organization",
      "name": "ruokeqx's blog",
      "url": "https://ruokeqx.gitee.io"
    }
  }
</script>

    
  
  







  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

    
</head>

<body id="root" class="theme__dark">
    <script>
        var localTheme = localStorage.getItem('theme');
        if (localTheme) {
            document.getElementById('root').className = 'theme__' + localTheme;
        }
    </script>
    <div id="container">
        





        <div class="wrapper" data-type="posts" data-kind="page">
            <nav class="navbar scrolling" role="navigation" aria-label="main navigation" data-dir="ltr">
  <div class="navbar__brand">
    
    <a href="/" title="Home" rel="home" class="navbar__logo-link">
      <img src="/logo.png" alt="Home" class="navbar__logo">
    </a>
    
    
      <a href="/" title="Home" rel="home" class="navbar__title-link">
        <h6 class="navbar__title">ruokeqx</h6>
      </a>
    
  </div>

  
<div class="theme theme-mobile" data-ani="true">
  <div class="dropdown">
    <button class="dropdown-trigger navbar__slide-down" aria-label="Select Theme Button" style="" data-ani="true">
      <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24"><path fill="none" d="M24 0H0v24h24V0z"/><path fill="currentColor" d="M6.34 7.93c-3.12 3.12-3.12 8.19 0 11.31C7.9 20.8 9.95 21.58 12 21.58s4.1-.78 5.66-2.34c3.12-3.12 3.12-8.19 0-11.31l-4.95-4.95c-.39-.39-1.02-.39-1.41 0L6.34 7.93zM12 19.59c-1.6 0-3.11-.62-4.24-1.76C6.62 16.69 6 15.19 6 13.59s.62-3.11 1.76-4.24L12 5.1v14.49z"/></svg>      
    </button>
    <div class="dropdown-content select-theme">
      
        
        <a href="#" class="dropdown-item select-theme__item is-active">
          dark
        </a>
        
        <a href="#" class="dropdown-item select-theme__item ">
          light
        </a>
        
        <a href="#" class="dropdown-item select-theme__item ">
          hacker
        </a>
        
        <a href="#" class="dropdown-item select-theme__item ">
          solarized
        </a>
        
        <a href="#" class="dropdown-item select-theme__item ">
          kimbie
        </a>
        
      
    </div>
  </div>
</div>


<div class="mobile-search__btn navbar-search" data-ani="true">
  <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" fill="currentColor" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0V0z"/><path d="M15.5 14h-.79l-.28-.27c1.2-1.4 1.82-3.31 1.48-5.34-.47-2.78-2.79-5-5.59-5.34-4.23-.52-7.79 3.04-7.27 7.27.34 2.8 2.56 5.12 5.34 5.59 2.03.34 3.94-.28 5.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/></svg>
</div>

<div id="search-mobile-container" class="mobile-search hide" data-dir="ltr">
  <div class="mobile-search__top">
    <input id="search-mobile" type="text" aria-label="Mobile Search" placeholder="Search" class="mobile-search__top--input"/>
    <div id="search-mobile-close" class="mobile-search__top--icon">
      <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24"><path opacity=".87" fill="none" d="M0 0h24v24H0V0z"/><path fill="currentColor" d="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm3.59-13L12 10.59 8.41 7 7 8.41 10.59 12 7 15.59 8.41 17 12 13.41 15.59 17 17 15.59 13.41 12 17 8.41z"/></svg>
    </div>
  </div>
  <div id="search-mobile-results" class="mobile-search__body">
    
  </div>
</div>


<a role="button" class="navbar__burger" aria-label="menu" aria-expanded="false"
  data-ani="true">
  <span aria-hidden="true"></span>
  <span aria-hidden="true"></span>
  <span aria-hidden="true"></span>
</a>
<div class="navbarm__collapse" data-open="false">
  <ul dir="ltr">
    
    
      
      
      
      

      
        <li class="navbarm__menu--item active">
          <a href="/posts">Posts</a>
        </li>
      
      
    
      
      
      
      

      
        <li class="navbarm__menu--item ">
          <a href="/archive">Archive</a>
        </li>
      
      
    
      
      
      
      

      
        <li class="navbarm__menu--item ">
          <a href="/about">About</a>
        </li>
      
      
    

    
      <li class="navbarm__menu--item ">
        <a href="/tags" class="navbarm__menu--term" data-index="0">
          Tags
        </a>
      </li>
    
      <li class="navbarm__menu--item ">
        <a href="/categories" class="navbarm__menu--term" data-index="1">
          Categories
        </a>
      </li>
    
      <li class="navbarm__menu--item ">
        <a href="/series" class="navbarm__menu--term" data-index="2">
          Series
        </a>
      </li>
    
  </ul>
</div>
  <div class="navbar__menu">
  
  
  
<div class="theme" data-ani="true">
  <div class="dropdown">
    <button class="dropdown-trigger navbar__slide-down" aria-label="Select Theme Button" data-ani="true">
      <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24"><path fill="none" d="M24 0H0v24h24V0z"/><path fill="currentColor" d="M6.34 7.93c-3.12 3.12-3.12 8.19 0 11.31C7.9 20.8 9.95 21.58 12 21.58s4.1-.78 5.66-2.34c3.12-3.12 3.12-8.19 0-11.31l-4.95-4.95c-.39-.39-1.02-.39-1.41 0L6.34 7.93zM12 19.59c-1.6 0-3.11-.62-4.24-1.76C6.62 16.69 6 15.19 6 13.59s.62-3.11 1.76-4.24L12 5.1v14.49z"/></svg>      
    </button>
    <div class="dropdown-content select-theme">
      
        
        <a href="#" class="dropdown-item select-theme__item is-active">
          dark
        </a>
        
        <a href="#" class="dropdown-item select-theme__item ">
          light
        </a>
        
        <a href="#" class="dropdown-item select-theme__item ">
          hacker
        </a>
        
        <a href="#" class="dropdown-item select-theme__item ">
          solarized
        </a>
        
        <a href="#" class="dropdown-item select-theme__item ">
          kimbie
        </a>
        
      
    </div>
  </div>
</div>

  
  
  
  
  
  
  
  <a href="/posts" class="navbar__menu-item navbar__slide-down active" dir="ltr" data-ani="true">Posts</a>
  
  
  
  
  
  
  
  <a href="/archive" class="navbar__menu-item navbar__slide-down " dir="ltr" data-ani="true">Archive</a>
  
  
  
  
  
  
  
  <a href="/about" class="navbar__menu-item navbar__slide-down " dir="ltr" data-ani="true">About</a>
  
  
</div>
</nav>
            
            

<main class="single__main main-main">
  
    <nav class="breadcrumb hide" aria-label="breadcrumbs">
  <script>document.querySelector('.breadcrumb').classList.remove('hide')</script>
  <ol>
    
  
  
  
  
  
  <li >
    
      <a href="https://ruokeqx.gitee.io/" class="capitalize">ruokeqx&#39;s blog</a>
    
  </li>
  
  
  <li >
    
      <a href="https://ruokeqx.gitee.io/posts/" class="capitalize">Posts</a>
    
  </li>
  
  
  <li  class="is-active" >
    
      <span>libpcap、tcpdump以及kernel/net的部分源码阅读</span>
    
  </li>
  
  </ol>
  
</nav>
  
  
  <div class="single ">
    <div class="single__nojs">This page looks best with JavaScript enabled</div>
    <script>document.querySelector('.single').classList.remove('hide'); document.querySelector('.single__nojs').classList.add('hide');</script>
    <h2 class="single__title" data-ani="true">libpcap、tcpdump以及kernel/net的部分源码阅读</h2>
    <h3 class="single__subtitle"></h3>
    <div class="single__meta">
      
<div class="single__infos">
  <time class="single__info" title="Written At">📅&nbsp;Mar 14, 2022 </time>
  
  &nbsp;&middot;&nbsp; <span class="single__info" title="Reading Time"> ☕&nbsp;17&nbsp;min read </span>
  
  <span class="single__info">
     &middot; 👀<span id="busuanzi_value_page_pv">...</span> views
  </span>
</div>

      
<ul class="single__tags caption">
  
  🏷️
  

  <li><a href="https://ruokeqx.gitee.io/tags/networking/" class="single__tag" title="networking">#networking</a></li>

  <li><a href="https://ruokeqx.gitee.io/tags/kernel/" class="single__tag" title="kernel">#kernel</a></li>

</ul>

    </div>
    <article class="single__contents" data-dir="ltr" data-ani="true">
      
      <h2 id="begin">Begin</h2>
<p>本文起因是操作系统课设任务新增系统调用，当时想法是新增一个网络抓包功能的系统调用，类似于简化版的tcpdump和kernel的缝合，所以就开始尝试阅读libpcap、tcpdunmp及kernel/net部分源码。由于系统代码量大，理清架构有一定难度，所以一直拖到现在才完成部分内容。</p>
<p>本文libpcap版本:1.10.1(阅读时最新的release[2021年12月])<br />
kernel5.15.6</p>
<p>抓包的历史主要分成两个</p>
<p>一个是远古版本socket(PF_INET)+recvfrom() 这样需要多次内存拷贝和系统调用 效率较低<br />
还有一个是现在使用的scoket(PF_PACKET)+memory-mapped 减少系统调用和内存拷贝 效率较高</p>
<h2 id="libpcap常用接口">libpcap常用接口</h2>
<p>一般情况下使用libpcap库抓包会用到下面几个接口函数</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span><span class="lnt">37
</span><span class="lnt">38
</span><span class="lnt">39
</span><span class="lnt">40
</span><span class="lnt">41
</span><span class="lnt">42
</span><span class="lnt">43
</span><span class="lnt">44
</span><span class="lnt">45
</span><span class="lnt">46
</span><span class="lnt">47
</span><span class="lnt">48
</span><span class="lnt">49
</span><span class="lnt">50
</span><span class="lnt">51
</span><span class="lnt">52
</span><span class="lnt">53
</span><span class="lnt">54
</span><span class="lnt">55
</span><span class="lnt">56
</span><span class="lnt">57
</span><span class="lnt">58
</span><span class="lnt">59
</span><span class="lnt">60
</span><span class="lnt">61
</span><span class="lnt">62
</span><span class="lnt">63
</span><span class="lnt">64
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="line"><span class="cl"><span class="c1">// 1.打开一个用于捕获数据的网络接口
</span></span></span><span class="line"><span class="cl"><span class="c1">// pcap.c
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="n">pcap_t</span>	<span class="o">*</span><span class="nf">pcap_open_live</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="p">,</span> <span class="kt">int</span><span class="p">,</span> <span class="kt">int</span><span class="p">,</span> <span class="kt">int</span><span class="p">,</span> <span class="kt">char</span> <span class="o">*</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="cm">/*
</span></span></span><span class="line"><span class="cl"><span class="cm">	const char * device	网络接口名字 为第一步获取的网络接口字符串(pcap_lookupdev()返回值),可人为指定,例如&#34;eth0&#34;
</span></span></span><span class="line"><span class="cl"><span class="cm">	int snaplen			捕获数据包长度
</span></span></span><span class="line"><span class="cl"><span class="cm">	int promise 		混杂模式-1 非混杂模式-0
</span></span></span><span class="line"><span class="cl"><span class="cm">	int to_ms			需要等待的毫秒数
</span></span></span><span class="line"><span class="cl"><span class="cm">	char *errbuf		存储错误信息
</span></span></span><span class="line"><span class="cl"><span class="cm">*/</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// 2.获取指定网卡的 ip 地址,子网掩码
</span></span></span><span class="line"><span class="cl"><span class="c1">// pcap.c
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kt">int</span>	<span class="nf">pcap_lookupnet</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="p">,</span> <span class="n">bpf_u_int32</span> <span class="o">*</span><span class="p">,</span> <span class="n">bpf_u_int32</span> <span class="o">*</span><span class="p">,</span> <span class="kt">char</span> <span class="o">*</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="cm">/*
</span></span></span><span class="line"><span class="cl"><span class="cm">	const char *device	网络设备名	可以人为指定eth0 可以是pcap_lookupdev()的返回值
</span></span></span><span class="line"><span class="cl"><span class="cm">	bpf_u_int32 *netp	存放ip的指针
</span></span></span><span class="line"><span class="cl"><span class="cm">	bpf_u_int32 *maskp	存放子网掩码的指针
</span></span></span><span class="line"><span class="cl"><span class="cm">	char *errbuf		存放错误信息
</span></span></span><span class="line"><span class="cl"><span class="cm">*/</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// 3.编译BPF过滤规则
</span></span></span><span class="line"><span class="cl"><span class="c1">// gencode.c
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kt">int</span>	<span class="nf">pcap_compile</span><span class="p">(</span><span class="n">pcap_t</span> <span class="o">*</span><span class="p">,</span> <span class="k">struct</span> <span class="n">bpf_program</span> <span class="o">*</span><span class="p">,</span> <span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="p">,</span> <span class="kt">int</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">	    <span class="n">bpf_u_int32</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="cm">/*
</span></span></span><span class="line"><span class="cl"><span class="cm">	pcap_t *p				pcap_open_live()创建并返回的 pcap_t 类型的指针
</span></span></span><span class="line"><span class="cl"><span class="cm">	struct bpf_program *fp	存放编译后的BPF pcap_setfilter()需要传入这个指针
</span></span></span><span class="line"><span class="cl"><span class="cm">	const char *buf			过滤条件
</span></span></span><span class="line"><span class="cl"><span class="cm">	int optimize			是否需要优化过滤表达式
</span></span></span><span class="line"><span class="cl"><span class="cm">	bpf_u_int32 mask		指定本地网络的网络掩码
</span></span></span><span class="line"><span class="cl"><span class="cm">*/</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// 4.设置过滤规则
</span></span></span><span class="line"><span class="cl"><span class="c1">// pcap.c
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kt">int</span>	<span class="nf">pcap_setfilter</span><span class="p">(</span><span class="n">pcap_t</span> <span class="o">*</span><span class="p">,</span> <span class="k">struct</span> <span class="n">bpf_program</span> <span class="o">*</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="cm">/*
</span></span></span><span class="line"><span class="cl"><span class="cm">	pcap_t *p				pcap_open_live()创建并返回的 pcap_t 类型的指针
</span></span></span><span class="line"><span class="cl"><span class="cm">	struct bpf_program *fp	pcap_compile()编译好的BPF过滤规则	[第二个参数]
</span></span></span><span class="line"><span class="cl"><span class="cm">*/</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// 5.循环捕获网络数据包
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kt">int</span>	<span class="nf">pcap_loop</span><span class="p">(</span><span class="n">pcap_t</span> <span class="o">*</span><span class="p">,</span> <span class="kt">int</span><span class="p">,</span> <span class="n">pcap_handler</span><span class="p">,</span> <span class="n">u_char</span> <span class="o">*</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="cm">/*
</span></span></span><span class="line"><span class="cl"><span class="cm">	pcap_t *p				pcap_open_live()创建并返回的 pcap_t 类型的指针
</span></span></span><span class="line"><span class="cl"><span class="cm">	int cnt					指定捕获数据包个数 抓到了指定数目就会立刻返回 -1无限循环捕获
</span></span></span><span class="line"><span class="cl"><span class="cm">	pcap_handler callback	回调函数,处理捕获到的数据包
</span></span></span><span class="line"><span class="cl"><span class="cm">	u_char *user			向回调中传递的参数
</span></span></span><span class="line"><span class="cl"><span class="cm">
</span></span></span><span class="line"><span class="cl"><span class="cm">	typedef void (*pcap_handler)(u_char *, const struct pcap_pkthdr *,
</span></span></span><span class="line"><span class="cl"><span class="cm">			     const u_char *);
</span></span></span><span class="line"><span class="cl"><span class="cm">				u_char * user						pcap_loop()最后一个参数
</span></span></span><span class="line"><span class="cl"><span class="cm">				const struct pcap_pkthdr *pkthdr	结构体指针 pcap_next()参数一致
</span></span></span><span class="line"><span class="cl"><span class="cm">				const u_char * packet				收到的数据包数据
</span></span></span><span class="line"><span class="cl"><span class="cm">*/</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">// 6.释放网络接口
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="kt">void</span> <span class="nf">pcap_close</span><span class="p">(</span><span class="n">pcap_t</span> <span class="o">*</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="cm">/*
</span></span></span><span class="line"><span class="cl"><span class="cm">	pcap_t *p	pcap_open_live()创建并返回的 pcap_t 类型的指针
</span></span></span><span class="line"><span class="cl"><span class="cm">*/</span>
</span></span></code></pre></td></tr></table>
</div>
</div><h2 id="抓包方式">抓包方式</h2>
<h3 id="socket--recvfrom">socket + recvfrom</h3>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="line"><span class="cl"><span class="n">sock</span> <span class="o">=</span> <span class="n">socket</span><span class="p">(</span><span class="n">PF_PACKET</span><span class="p">,</span> <span class="n">SOCK_RAW</span><span class="p">,</span> <span class="n">htons</span><span class="p">(</span><span class="n">ETH_P_ALL</span><span class="p">));</span>
</span></span><span class="line"><span class="cl"><span class="n">len</span> <span class="o">=</span> <span class="n">recvfrom</span><span class="p">(</span><span class="n">sock</span><span class="p">,</span> <span class="n">buffer</span><span class="p">,</span> <span class="n">BUFFER_MAX</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="n">buffer</span>
</span></span></code></pre></td></tr></table>
</div>
</div><h3 id="tcpdump">Tcpdump</h3>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="line"><span class="cl"><span class="kt">int</span> <span class="n">main</span><span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="p">...</span>
</span></span><span class="line"><span class="cl">	<span class="n">pc</span> <span class="o">=</span> <span class="n">pcap_create</span><span class="p">(</span><span class="n">device</span><span class="p">,</span> <span class="n">ebuf</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="p">...</span>
</span></span><span class="line"><span class="cl">	<span class="n">status</span> <span class="o">=</span> <span class="n">pcap_activate</span><span class="p">(</span><span class="n">pc</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="p">...</span>
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">WFileName</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">		<span class="p">...</span>
</span></span><span class="line"><span class="cl">		<span class="k">if</span> <span class="p">(</span><span class="n">Cflag</span> <span class="o">!=</span> <span class="mi">0</span> <span class="o">||</span> <span class="n">Gflag</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">			<span class="p">...</span>
</span></span><span class="line"><span class="cl">			<span class="n">callback</span> <span class="o">=</span> <span class="n">dump_packet_and_trunc</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">			<span class="p">...</span>
</span></span><span class="line"><span class="cl">		<span class="p">}</span><span class="k">else</span><span class="p">{</span>
</span></span><span class="line"><span class="cl">			<span class="n">callback</span> <span class="o">=</span> <span class="n">dump_packet</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">			<span class="p">...</span>
</span></span><span class="line"><span class="cl">		<span class="p">}</span>
</span></span><span class="line"><span class="cl">	<span class="p">}</span><span class="k">else</span><span class="p">{</span>
</span></span><span class="line"><span class="cl">		<span class="p">...</span>
</span></span><span class="line"><span class="cl">		<span class="n">callback</span> <span class="o">=</span> <span class="n">print_packet</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">		<span class="p">...</span>
</span></span><span class="line"><span class="cl">	<span class="p">}</span>
</span></span><span class="line"><span class="cl">	<span class="p">...</span>
</span></span><span class="line"><span class="cl">	<span class="k">do</span><span class="p">{</span>
</span></span><span class="line"><span class="cl">		<span class="n">status</span> <span class="o">=</span> <span class="n">pcap_loop</span><span class="p">(</span><span class="n">pd</span><span class="p">,</span> <span class="n">cnt</span><span class="p">,</span> <span class="n">callback</span><span class="p">,</span> <span class="n">pcap_userdata</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">		<span class="p">...</span>
</span></span><span class="line"><span class="cl">	<span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><h3 id="例程-pcap_loop">例程-pcap_loop</h3>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span><span class="lnt">37
</span><span class="lnt">38
</span><span class="lnt">39
</span><span class="lnt">40
</span><span class="lnt">41
</span><span class="lnt">42
</span><span class="lnt">43
</span><span class="lnt">44
</span><span class="lnt">45
</span><span class="lnt">46
</span><span class="lnt">47
</span><span class="lnt">48
</span><span class="lnt">49
</span><span class="lnt">50
</span><span class="lnt">51
</span><span class="lnt">52
</span><span class="lnt">53
</span><span class="lnt">54
</span><span class="lnt">55
</span><span class="lnt">56
</span><span class="lnt">57
</span><span class="lnt">58
</span><span class="lnt">59
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="line"><span class="cl"><span class="k">static</span> <span class="kt">void</span> <span class="nf">ethernet_packet</span><span class="p">(</span><span class="n">u_char</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="k">const</span> <span class="k">struct</span> <span class="n">pcap_pkthdr</span> <span class="o">*</span><span class="n">header</span><span class="p">,</span> <span class="k">const</span> <span class="n">u_char</span> <span class="o">*</span><span class="n">packet</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="c1">// 程序对抓到包的处理
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="k">return</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">static</span> <span class="kt">void</span> <span class="o">*</span> <span class="nf">sniffer_thread_callback</span><span class="p">(</span><span class="kt">void</span> <span class="o">*</span><span class="n">param</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="n">pthread_detach</span><span class="p">(</span><span class="n">pthread_self</span><span class="p">());</span>
</span></span><span class="line"><span class="cl">	<span class="n">printf</span><span class="p">(</span><span class="s">&#34;sniffer_thread_callback enter</span><span class="se">\n</span><span class="s">&#34;</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span> <span class="n">nDev</span> <span class="o">=-</span><span class="p">(</span><span class="n">TYPE32</span><span class="p">)</span><span class="n">param</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="kt">char</span> <span class="n">errbuf</span><span class="p">[</span><span class="n">PCAP_ERRBUF_SIZE</span><span class="p">];</span>
</span></span><span class="line"><span class="cl">	<span class="n">pcap_t</span> <span class="o">*</span><span class="n">handle</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="c1">//bug  modify flag  jl
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="kt">char</span> <span class="o">*</span><span class="n">filter_exp</span> <span class="o">=</span> <span class="s">&#34;not broadcast and not arp&#34;</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">struct</span> <span class="n">bpf_program</span> <span class="n">fp</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">bpf_u_int32</span> <span class="n">mask</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">bpf_u_int32</span> <span class="n">net</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">handle</span> <span class="o">=</span> <span class="n">pcap_open_live</span><span class="p">(</span><span class="n">option_struct</span><span class="p">.</span><span class="n">dev_interface</span><span class="p">[</span><span class="n">nDev</span><span class="p">],</span> <span class="mi">65535</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="n">errbuf</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">handle</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">		<span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&#34;couldn&#39;t open device %s: %s</span><span class="se">\n</span><span class="s">&#34;</span><span class="p">,</span> <span class="n">option_struct</span><span class="p">.</span><span class="n">dev_interface</span><span class="p">[</span><span class="n">nDev</span><span class="p">],</span> <span class="n">errbuf</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">		<span class="n">pthread_exit</span><span class="p">(</span><span class="nb">NULL</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">		<span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">pcap_lookupnet</span><span class="p">(</span><span class="n">option_struct</span><span class="p">.</span><span class="n">dev_interface</span><span class="p">[</span><span class="n">nDev</span><span class="p">],</span> <span class="o">&amp;</span><span class="n">net</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">mask</span><span class="p">,</span> <span class="n">errbuf</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">pcap_datalink</span><span class="p">(</span><span class="n">handle</span><span class="p">)</span> <span class="o">!=</span> <span class="n">DLT_EN10MB</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">		<span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&#34;couldn&#39;t pcap_datalink %s</span><span class="se">\n</span><span class="s">&#34;</span><span class="p">,</span> <span class="n">pcap_geterr</span><span class="p">(</span><span class="n">handle</span><span class="p">));</span>
</span></span><span class="line"><span class="cl">		<span class="n">pcap_close</span><span class="p">(</span><span class="n">handle</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">		<span class="n">pthread_exit</span><span class="p">(</span><span class="nb">NULL</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">		<span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="p">}</span>
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">pcap_compile</span><span class="p">(</span><span class="n">handle</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">fp</span><span class="p">,</span> <span class="n">filter_exp</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="n">net</span><span class="p">)</span> <span class="o">==</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">		<span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&#34;couldn&#39;t parse filter %s: %s</span><span class="se">\n</span><span class="s">&#34;</span><span class="p">,</span> <span class="n">filter_exp</span><span class="p">,</span> <span class="n">pcap_geterr</span><span class="p">(</span><span class="n">handle</span><span class="p">));</span>
</span></span><span class="line"><span class="cl">		<span class="n">pcap_freecode</span><span class="p">(</span><span class="o">&amp;</span><span class="n">fp</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">		<span class="n">pcap_close</span><span class="p">(</span><span class="n">handle</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">		<span class="n">pthread_exit</span><span class="p">(</span><span class="nb">NULL</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">		<span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">pcap_setfilter</span><span class="p">(</span><span class="n">handle</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">fp</span><span class="p">)</span> <span class="o">==</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">		<span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&#34;couldn&#39;t install filter %s: %s</span><span class="se">\n</span><span class="s">&#34;</span><span class="p">,</span> <span class="n">filter_exp</span><span class="p">,</span> <span class="n">pcap_geterr</span><span class="p">(</span><span class="n">handle</span><span class="p">));</span>
</span></span><span class="line"><span class="cl">		<span class="n">pcap_freecode</span><span class="p">(</span><span class="o">&amp;</span><span class="n">fp</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">		<span class="n">pcap_close</span><span class="p">(</span><span class="n">handle</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">		<span class="n">pthread_exit</span><span class="p">(</span><span class="nb">NULL</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">		<span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">pcap_loop</span><span class="p">(</span><span class="n">handle</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="n">ethernet_packet</span><span class="p">,</span> <span class="p">(</span><span class="n">u_char</span> <span class="o">*</span><span class="p">)</span><span class="o">&amp;</span><span class="n">nDev</span><span class="p">)</span> <span class="o">==</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">		<span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&#34;couldn&#39;t pacp loop  %s: %s</span><span class="se">\n</span><span class="s">&#34;</span><span class="p">,</span> <span class="n">filter_exp</span><span class="p">,</span> <span class="n">pcap_geterr</span><span class="p">(</span><span class="n">handle</span><span class="p">));</span>
</span></span><span class="line"><span class="cl">	<span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">pcap_freecode</span><span class="p">(</span><span class="o">&amp;</span><span class="n">fp</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="n">pcap_close</span><span class="p">(</span><span class="n">handle</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="n">pthread_exit</span><span class="p">(</span><span class="nb">NULL</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><h2 id="libpcap结构体">libpcap结构体</h2>
<p>使用的重要结构体如下</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span><span class="lnt">37
</span><span class="lnt">38
</span><span class="lnt">39
</span><span class="lnt">40
</span><span class="lnt">41
</span><span class="lnt">42
</span><span class="lnt">43
</span><span class="lnt">44
</span><span class="lnt">45
</span><span class="lnt">46
</span><span class="lnt">47
</span><span class="lnt">48
</span><span class="lnt">49
</span><span class="lnt">50
</span><span class="lnt">51
</span><span class="lnt">52
</span><span class="lnt">53
</span><span class="lnt">54
</span><span class="lnt">55
</span><span class="lnt">56
</span><span class="lnt">57
</span><span class="lnt">58
</span><span class="lnt">59
</span><span class="lnt">60
</span><span class="lnt">61
</span><span class="lnt">62
</span><span class="lnt">63
</span><span class="lnt">64
</span><span class="lnt">65
</span><span class="lnt">66
</span><span class="lnt">67
</span><span class="lnt">68
</span><span class="lnt">69
</span><span class="lnt">70
</span><span class="lnt">71
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="line"><span class="cl"><span class="c1">// pcap-int.h
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">struct</span> <span class="n">pcap</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="n">read_op_t</span> <span class="n">read_op</span><span class="p">;</span> <span class="c1">// Method to call to read packets on a live capture.
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="n">next_packet_op_t</span> <span class="n">next_packet_op</span><span class="p">;</span> <span class="c1">// Method to call to read the next packet from a savefile.
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>
</span></span><span class="line"><span class="cl">	<span class="cm">/*
</span></span></span><span class="line"><span class="cl"><span class="cm">	 * Read buffer.
</span></span></span><span class="line"><span class="cl"><span class="cm">	 */</span>
</span></span><span class="line"><span class="cl">	<span class="n">u_int</span> <span class="n">bufsize</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">void</span> <span class="o">*</span><span class="n">buffer</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">u_char</span> <span class="o">*</span><span class="n">bp</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span> <span class="n">cc</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">sig_atomic_t</span> <span class="n">break_loop</span><span class="p">;</span> <span class="cm">/* flag set to force break from packet-reading loop */</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="kt">void</span> <span class="o">*</span><span class="n">priv</span><span class="p">;</span>		<span class="cm">/* private data for methods */</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="c1">// ...
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="c1">// pcap-int.h
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">struct</span> <span class="n">pcap_opt</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="kt">char</span>	<span class="o">*</span><span class="n">device</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span>	<span class="n">timeout</span><span class="p">;</span>	<span class="cm">/* timeout for buffering */</span>
</span></span><span class="line"><span class="cl">	<span class="n">u_int</span>	<span class="n">buffer_size</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span>	<span class="n">promisc</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span>	<span class="n">rfmon</span><span class="p">;</span>		<span class="cm">/* monitor mode */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span>	<span class="n">immediate</span><span class="p">;</span>	<span class="cm">/* immediate mode - deliver packets as soon as they arrive */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span>	<span class="n">nonblock</span><span class="p">;</span>	<span class="cm">/* non-blocking mode - don&#39;t wait for packets to be delivered, return &#34;no packets available&#34; */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span>	<span class="n">tstamp_type</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span>	<span class="n">tstamp_precision</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1">// linux
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="kt">int</span>	<span class="n">protocol</span><span class="p">;</span>	<span class="cm">/* protocol to use when creating PF_PACKET socket */</span>
</span></span><span class="line"><span class="cl">    <span class="c1">// WIN32
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="kt">int</span>	<span class="n">nocapture_local</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">};</span>
</span></span><span class="line"><span class="cl"><span class="c1">// pcap-linux.c
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">struct</span> <span class="n">pcap_linux</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="kt">long</span> <span class="kt">long</span> <span class="n">sysfs_dropped</span><span class="p">;</span> <span class="cm">/* packets reported dropped by /sys/class/net/{if_name}/statistics/rx_{missed,fifo}_errors */</span>
</span></span><span class="line"><span class="cl">	<span class="k">struct</span> <span class="n">pcap_stat</span> <span class="n">stat</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="kt">char</span>	<span class="o">*</span><span class="n">device</span><span class="p">;</span>	<span class="cm">/* device name */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span>	<span class="n">filter_in_userland</span><span class="p">;</span> <span class="cm">/* must filter in userland */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span>	<span class="n">blocks_to_filter_in_userland</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span>	<span class="n">must_do_on_close</span><span class="p">;</span> <span class="cm">/* stuff we must do when we close */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span>	<span class="n">timeout</span><span class="p">;</span>	<span class="cm">/* timeout for buffering */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span>	<span class="n">cooked</span><span class="p">;</span>		<span class="cm">/* using SOCK_DGRAM rather than SOCK_RAW */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span>	<span class="n">ifindex</span><span class="p">;</span>	<span class="cm">/* interface index of device we&#39;re bound to */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span>	<span class="n">lo_ifindex</span><span class="p">;</span>	<span class="cm">/* interface index of the loopback device */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span>	<span class="n">netdown</span><span class="p">;</span>	<span class="cm">/* we got an ENETDOWN and haven&#39;t resolved it */</span>
</span></span><span class="line"><span class="cl">	<span class="n">bpf_u_int32</span> <span class="n">oldmode</span><span class="p">;</span>	<span class="cm">/* mode to restore when turning monitor mode off */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">char</span>	<span class="o">*</span><span class="n">mondevice</span><span class="p">;</span>	<span class="cm">/* mac80211 monitor device we created */</span>
</span></span><span class="line"><span class="cl">	<span class="n">u_char</span>	<span class="o">*</span><span class="n">mmapbuf</span><span class="p">;</span>	<span class="cm">/* memory-mapped region pointer */</span>
</span></span><span class="line"><span class="cl">	<span class="n">size_t</span>	<span class="n">mmapbuflen</span><span class="p">;</span>	<span class="cm">/* size of region */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span>	<span class="n">vlan_offset</span><span class="p">;</span>	<span class="cm">/* offset at which to insert vlan tags; if -1, don&#39;t insert */</span>
</span></span><span class="line"><span class="cl">	<span class="n">u_int</span>	<span class="n">tp_version</span><span class="p">;</span>	<span class="cm">/* version of tpacket_hdr for mmaped ring */</span>
</span></span><span class="line"><span class="cl">	<span class="n">u_int</span>	<span class="n">tp_hdrlen</span><span class="p">;</span>	<span class="cm">/* hdrlen of tpacket_hdr for mmaped ring */</span>
</span></span><span class="line"><span class="cl">	<span class="n">u_char</span>	<span class="o">*</span><span class="n">oneshot_buffer</span><span class="p">;</span> <span class="cm">/* buffer for copy of packet */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span>	<span class="n">poll_timeout</span><span class="p">;</span>	<span class="cm">/* timeout to use in poll() */</span>
</span></span><span class="line"><span class="cl"><span class="cp">#ifdef HAVE_TPACKET3
</span></span></span><span class="line"><span class="cl"><span class="cp"></span>	<span class="kt">unsigned</span> <span class="kt">char</span> <span class="o">*</span><span class="n">current_packet</span><span class="p">;</span> <span class="cm">/* Current packet within the TPACKET_V3 block. Move to next block if NULL. */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span> <span class="n">packets_left</span><span class="p">;</span> <span class="cm">/* Unhandled packets left within the block from previous call to pcap_read_linux_mmap_v3 in case of TPACKET_V3. */</span>
</span></span><span class="line"><span class="cl"><span class="cp">#endif
</span></span></span><span class="line"><span class="cl"><span class="cp"></span>	<span class="kt">int</span> <span class="n">poll_breakloop_fd</span><span class="p">;</span> <span class="cm">/* fd to an eventfd to break from blocking operations */</span>
</span></span><span class="line"><span class="cl"><span class="p">};</span>
</span></span><span class="line"><span class="cl"><span class="c1">// pcap/pcap.h
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">struct</span> <span class="n">pcap_pkthdr</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="k">struct</span> <span class="n">timeval</span> <span class="n">ts</span><span class="p">;</span>	<span class="cm">/* time stamp */</span>
</span></span><span class="line"><span class="cl">	<span class="n">bpf_u_int32</span> <span class="n">caplen</span><span class="p">;</span>	<span class="cm">/* length of portion present */</span>
</span></span><span class="line"><span class="cl">	<span class="n">bpf_u_int32</span> <span class="n">len</span><span class="p">;</span>	<span class="cm">/* length of this packet (off wire) */</span>
</span></span><span class="line"><span class="cl"><span class="p">};</span>
</span></span></code></pre></td></tr></table>
</div>
</div><h2 id="pcap_open_live">pcap_open_live</h2>
<p>pcap_open_live简略代码如下,可以认为只调用了两个函数,一个pcap_create,一个pcap_activate</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="line"><span class="cl"><span class="n">pcap_t</span> <span class="o">*</span>
</span></span><span class="line"><span class="cl"><span class="nf">pcap_open_live</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">device</span><span class="p">,</span> <span class="kt">int</span> <span class="n">snaplen</span><span class="p">,</span> <span class="kt">int</span> <span class="n">promisc</span><span class="p">,</span> <span class="kt">int</span> <span class="n">to_ms</span><span class="p">,</span> <span class="kt">char</span> <span class="o">*</span><span class="n">errbuf</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="n">pcap_t</span> <span class="o">*</span><span class="n">p</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span> <span class="n">status</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">p</span> <span class="o">=</span> <span class="n">pcap_create</span><span class="p">(</span><span class="n">device</span><span class="p">,</span> <span class="n">errbuf</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="c1">// 省略p设置默认值
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="n">status</span> <span class="o">=</span> <span class="n">pcap_activate</span><span class="p">(</span><span class="n">p</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="k">return</span> <span class="n">p</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><h3 id="pcap_create">pcap_create</h3>
<p>pcap_create()调用链如下,设置了两个函数指针,一个是activate_op,为后续activate<br />
另一个开启了无线模式(默认pcap_create_common创建时关闭的)<br />
configure中默认是$as_echo &ldquo;#define HAVE_LIBNL 1&rdquo; &raquo;confdefs.h<br />
然后pcap_can_set_rfmon_linux()检测<code>mac80211 device</code>,如果存在就默认支持无线模式</p>
<pre tabindex="0"><code>pcap_open_live()中[p = pcap_create(device, errbuf);]-&gt;pcap_create()-&gt;pcap_create_interface()-&gt;pcap_create_common()
// pcap-linux.c中pcap_create_interface()为pcap_t设置具体函数指针,主要是下面两个
handle-&gt;activate_op = pcap_activate_linux;
handle-&gt;can_set_rfmon_op = pcap_can_set_rfmon_linux;
</code></pre><p>pcap_create()简化代码如下<br />
tcpdump的main函数就是直接调用pcap_create()和pcap_activate(),然后用pcap_loop()循环收包<br />
<a href="https://github.com/the-tcpdump-group/tcpdump/blob/master/tcpdump.c#L1270">https://github.com/the-tcpdump-group/tcpdump/blob/master/tcpdump.c#L1270</a><br />
<a href="https://github.com/the-tcpdump-group/tcpdump/blob/master/tcpdump.c#L2600">https://github.com/the-tcpdump-group/tcpdump/blob/master/tcpdump.c#L2600</a></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="line"><span class="cl"><span class="n">pcap_t</span> <span class="o">*</span>
</span></span><span class="line"><span class="cl"><span class="nf">pcap_create</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">device</span><span class="p">,</span> <span class="kt">char</span> <span class="o">*</span><span class="n">errbuf</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="n">size_t</span> <span class="n">i</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span> <span class="n">is_theirs</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">pcap_t</span> <span class="o">*</span><span class="n">p</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">char</span> <span class="o">*</span><span class="n">device_str</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">device</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">		<span class="n">device_str</span> <span class="o">=</span> <span class="p">(</span><span class="s">&#34;any&#34;</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="k">else</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">		<span class="n">device_str</span> <span class="o">=</span> <span class="n">strdup</span><span class="p">(</span><span class="n">device</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">p</span> <span class="o">=</span> <span class="n">pcap_create_interface</span><span class="p">(</span><span class="n">device_str</span><span class="p">,</span> <span class="n">errbuf</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="n">p</span><span class="o">-&gt;</span><span class="n">opt</span><span class="p">.</span><span class="n">device</span> <span class="o">=</span> <span class="n">device_str</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">return</span> <span class="p">(</span><span class="n">p</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><h3 id="pcap_activate">pcap_activate</h3>
<p>pcap_activate()调用链如下,pcap_t的active_op方法,启用之前设置的pcap_activate_linux,接着调用activate_pf_packet,其中用socket系统调用创建原始套接字</p>
<pre tabindex="0"><code>&lt;!-- pcap_open_live()中[status = pcap_activate(p);] --&gt;
pcap_activate()-&gt;pcap_activate_linux()-&gt;activate_pf_packet()-&gt;socket()
										-&gt;setup_mmapped()-&gt;prepare_tpacket_socket()-&gt;init_tpacket()-&gt;getsockopt()&amp;setsockopt()
														-&gt;create_ring()
</code></pre><div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="line"><span class="cl"><span class="c1">// pcap_activate()
</span></span></span><span class="line"><span class="cl"><span class="c1">// 调用上面pcap_open_live()调用的pcap_create_interface()中创建的函数指针 pcap_activate_linux;
</span></span></span><span class="line"><span class="cl"><span class="c1">// 并且检测是否设置了non-blocking mode,是的话就调用pcap_activate_linux()中设置的函数指针pcap_setnonblock_linux
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="n">status</span> <span class="o">=</span> <span class="n">p</span><span class="o">-&gt;</span><span class="n">activate_op</span><span class="p">(</span><span class="n">p</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="n">status</span> <span class="o">=</span> <span class="n">p</span><span class="o">-&gt;</span><span class="n">setnonblock_op</span><span class="p">(</span><span class="n">p</span><span class="p">,</span> <span class="mi">1</span><span class="p">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>pcap_activate()简化代码如下</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="line"><span class="cl"><span class="kt">int</span>
</span></span><span class="line"><span class="cl"><span class="nf">pcap_activate</span><span class="p">(</span><span class="n">pcap_t</span> <span class="o">*</span><span class="n">p</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span> <span class="n">status</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">status</span> <span class="o">=</span> <span class="n">p</span><span class="o">-&gt;</span><span class="n">activate_op</span><span class="p">(</span><span class="n">p</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="c1">// 如果调用pcap_activate()前设置了non-blocking mode, 现在打开它
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="k">if</span> <span class="p">(</span><span class="n">p</span><span class="o">-&gt;</span><span class="n">opt</span><span class="p">.</span><span class="n">nonblock</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">		<span class="n">status</span> <span class="o">=</span> <span class="n">p</span><span class="o">-&gt;</span><span class="n">setnonblock_op</span><span class="p">(</span><span class="n">p</span><span class="p">,</span> <span class="mi">1</span><span class="p">);</span>	<span class="c1">// 调用pcap_setnonblock_linux
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="p">}</span>
</span></span><span class="line"><span class="cl">	<span class="n">p</span><span class="o">-&gt;</span><span class="n">activated</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">return</span> <span class="p">(</span><span class="n">status</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="line"><span class="cl"><span class="c1">// pcap_activate_linux()
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="c1">// ......
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="n">ret</span> <span class="o">=</span> <span class="n">activate_pf_packet</span><span class="p">(</span><span class="n">handle</span><span class="p">,</span> <span class="n">is_any_device</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="c1">// ......
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="n">ret</span> <span class="o">=</span> <span class="n">setup_mmapped</span><span class="p">(</span><span class="n">handle</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">status</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="c1">// 实现一系列函数指针的赋值
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="c1">// 捕获包会调用这个接口
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="c1">// 内核mmap的方式来抓取报文
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="c1">// PACKET_MMAP非常高效,它提供一个映射到用户空间的大小可配置的ring buffer
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="c1">// 这种方式,读取报文只需要等待报文就可以了,大部分情况下不需要系统调用
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="c1">// 通过内核空间和用户空间共享的缓冲区还可以起到减少数据拷贝的作用
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	
</span></span><span class="line"><span class="cl">	<span class="k">switch</span> <span class="p">(</span><span class="n">handlep</span><span class="o">-&gt;</span><span class="n">tp_version</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="k">case</span> <span class="nl">TPACKET_V2</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">		<span class="n">handle</span><span class="o">-&gt;</span><span class="n">read_op</span> <span class="o">=</span> <span class="n">pcap_read_linux_mmap_v2</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">		<span class="k">break</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="cp">#ifdef HAVE_TPACKET3
</span></span></span><span class="line"><span class="cl"><span class="cp"></span>	<span class="k">case</span> <span class="nl">TPACKET_V3</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">		<span class="n">handle</span><span class="o">-&gt;</span><span class="n">read_op</span> <span class="o">=</span> <span class="n">pcap_read_linux_mmap_v3</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">		<span class="k">break</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="cp">#endif
</span></span></span><span class="line"><span class="cl"><span class="cp"></span>	<span class="p">}</span>
</span></span><span class="line"><span class="cl">	<span class="c1">// centos 7是关闭v3的
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="c1">// * Tue Dec 02 2014 Michal Sekletar &lt;msekleta@redhat.com&gt; - 14:1.5.3-4
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="c1">// - disable TPACKET_V3 memory mapped packet capture on AF_PACKET socket, use TPACKET_V2 instead (#1085096)
</span></span></span></code></pre></td></tr></table>
</div>
</div><h4 id="activate_pf_packet">activate_pf_packet</h4>
<p>简单来说就是创建PF_PACKET套接字</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="line"><span class="cl"><span class="c1">// activate_pf_packet()
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="n">sock_fd</span> <span class="o">=</span> <span class="n">is_any_device</span> <span class="o">?</span>
</span></span><span class="line"><span class="cl">		<span class="n">socket</span><span class="p">(</span><span class="n">PF_PACKET</span><span class="p">,</span> <span class="n">SOCK_DGRAM</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span> <span class="o">:</span>
</span></span><span class="line"><span class="cl">		<span class="n">socket</span><span class="p">(</span><span class="n">PF_PACKET</span><span class="p">,</span> <span class="n">SOCK_RAW</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="p">...</span>
</span></span><span class="line"><span class="cl">	<span class="n">handle</span><span class="o">-&gt;</span><span class="n">fd</span> <span class="o">=</span> <span class="n">sock_fd</span><span class="p">;</span>
</span></span></code></pre></td></tr></table>
</div>
</div><h4 id="setup_mmapped">setup_mmapped</h4>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="line"><span class="cl"><span class="c1">// pcap-linux.c
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">static</span> <span class="kt">int</span>
</span></span><span class="line"><span class="cl"><span class="nf">setup_mmapped</span><span class="p">(</span><span class="n">pcap_t</span> <span class="o">*</span><span class="n">handle</span><span class="p">,</span> <span class="kt">int</span> <span class="o">*</span><span class="n">status</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="k">struct</span> <span class="n">pcap_linux</span> <span class="o">*</span><span class="n">handlep</span> <span class="o">=</span> <span class="n">handle</span><span class="o">-&gt;</span><span class="n">priv</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span> <span class="n">ret</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="cm">/*
</span></span></span><span class="line"><span class="cl"><span class="cm">	 * Attempt to allocate a buffer to hold the contents of one
</span></span></span><span class="line"><span class="cl"><span class="cm">	 * packet, for use by the oneshot callback.
</span></span></span><span class="line"><span class="cl"><span class="cm">	 */</span>
</span></span><span class="line"><span class="cl">	<span class="n">handlep</span><span class="o">-&gt;</span><span class="n">oneshot_buffer</span> <span class="o">=</span> <span class="n">malloc</span><span class="p">(</span><span class="n">handle</span><span class="o">-&gt;</span><span class="n">snapshot</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="c1">// ...
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">handle</span><span class="o">-&gt;</span><span class="n">opt</span><span class="p">.</span><span class="n">buffer_size</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">		<span class="cm">/* 默认申请 2M 的ring buffer */</span>
</span></span><span class="line"><span class="cl">		<span class="n">handle</span><span class="o">-&gt;</span><span class="n">opt</span><span class="p">.</span><span class="n">buffer_size</span> <span class="o">=</span> <span class="mi">2</span><span class="o">*</span><span class="mi">1024</span><span class="o">*</span><span class="mi">1024</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="p">}</span>
</span></span><span class="line"><span class="cl">	<span class="n">ret</span> <span class="o">=</span> <span class="n">prepare_tpacket_socket</span><span class="p">(</span><span class="n">handle</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="c1">// ...
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="n">ret</span> <span class="o">=</span> <span class="n">create_ring</span><span class="p">(</span><span class="n">handle</span><span class="p">,</span> <span class="n">status</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="c1">// ...
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>
</span></span><span class="line"><span class="cl">	<span class="cm">/*
</span></span></span><span class="line"><span class="cl"><span class="cm">	 * handle-&gt;offset is used to get the current position into the rx ring.
</span></span></span><span class="line"><span class="cl"><span class="cm">	 * handle-&gt;cc is used to store the ring size.
</span></span></span><span class="line"><span class="cl"><span class="cm">	 */</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="cm">/*
</span></span></span><span class="line"><span class="cl"><span class="cm">	 * Set the timeout to use in poll() before returning.
</span></span></span><span class="line"><span class="cl"><span class="cm">	 */</span>
</span></span><span class="line"><span class="cl">	<span class="n">set_poll_timeout</span><span class="p">(</span><span class="n">handlep</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="k">return</span> <span class="mi">1</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>prepare_tpacket_socket()中根据配置是否支持TPACKET_V3来调用init_tpacket(),没有v3的话就尝试v2,v2的init_tpacket()返回值-1失败0成功1内核版本过老支持MMAP但不支持v2.</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="line"><span class="cl"><span class="c1">// pcap-linux.c
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">static</span> <span class="kt">int</span> <span class="nf">prepare_tpacket_socket</span><span class="p">(</span><span class="n">pcap_t</span> <span class="o">*</span><span class="n">handle</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span> <span class="n">ret</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="cp">#ifdef HAVE_TPACKET3
</span></span></span><span class="line"><span class="cl"><span class="cp"></span>	<span class="n">ret</span> <span class="o">=</span> <span class="n">init_tpacket</span><span class="p">(</span><span class="n">handle</span><span class="p">,</span> <span class="n">TPACKET_V3</span><span class="p">,</span> <span class="s">&#34;TPACKET_V3&#34;</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="k">return</span> <span class="n">ret</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="cp">#endif
</span></span></span><span class="line"><span class="cl"><span class="cp"></span>	<span class="n">ret</span> <span class="o">=</span> <span class="n">init_tpacket</span><span class="p">(</span><span class="n">handle</span><span class="p">,</span> <span class="n">TPACKET_V2</span><span class="p">,</span> <span class="s">&#34;TPACKET_V2&#34;</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="k">return</span> <span class="n">ret</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>init_tpacket 探测内核是否支持指定的TPACKET版本 支持的话就通过系统调用初始化tpacket 没啥好说的</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="line"><span class="cl"><span class="c1">// pcap-linux.c
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">static</span> <span class="kt">int</span>
</span></span><span class="line"><span class="cl"><span class="nf">init_tpacket</span><span class="p">(</span><span class="n">pcap_t</span> <span class="o">*</span><span class="n">handle</span><span class="p">,</span> <span class="kt">int</span> <span class="n">version</span><span class="p">,</span> <span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">version_str</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="k">struct</span> <span class="n">pcap_linux</span> <span class="o">*</span><span class="n">handlep</span> <span class="o">=</span> <span class="n">handle</span><span class="o">-&gt;</span><span class="n">priv</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span> <span class="n">val</span> <span class="o">=</span> <span class="n">version</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">socklen_t</span> <span class="n">len</span> <span class="o">=</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">val</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">getsockopt</span><span class="p">(</span><span class="n">handle</span><span class="o">-&gt;</span><span class="n">fd</span><span class="p">,</span> <span class="n">SOL_PACKET</span><span class="p">,</span> <span class="n">PACKET_HDRLEN</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">val</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">len</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">		<span class="n">err</span><span class="p">...</span>
</span></span><span class="line"><span class="cl">	<span class="p">}</span>
</span></span><span class="line"><span class="cl">	<span class="cm">/* hdrlen of tpacket_hdr for mmaped ring */</span>
</span></span><span class="line"><span class="cl">	<span class="n">handlep</span><span class="o">-&gt;</span><span class="n">tp_hdrlen</span> <span class="o">=</span> <span class="n">val</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">val</span> <span class="o">=</span> <span class="n">version</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">setsockopt</span><span class="p">(</span><span class="n">handle</span><span class="o">-&gt;</span><span class="n">fd</span><span class="p">,</span> <span class="n">SOL_PACKET</span><span class="p">,</span> <span class="n">PACKET_VERSION</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">val</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">val</span><span class="p">))</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">		<span class="n">err</span><span class="p">...</span>
</span></span><span class="line"><span class="cl">	<span class="p">}</span>
</span></span><span class="line"><span class="cl">	<span class="cm">/* version of tpacket_hdr for mmaped ring */</span>
</span></span><span class="line"><span class="cl">	<span class="n">handlep</span><span class="o">-&gt;</span><span class="n">tp_version</span> <span class="o">=</span> <span class="n">version</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>create_ring()主要是环的创建<br />
先是根据版本创建对应tpacket_req结构体并设置参数<br />
然后通过setsockopt设置PACKET_RX_RING<br />
memory map the rx ring(mmap是系统调用)<br />
创建一个环，然后为环中每个header设置frame ptr</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span><span class="lnt">37
</span><span class="lnt">38
</span><span class="lnt">39
</span><span class="lnt">40
</span><span class="lnt">41
</span><span class="lnt">42
</span><span class="lnt">43
</span><span class="lnt">44
</span><span class="lnt">45
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="line"><span class="cl"><span class="c1">// create_ring()
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">struct</span> <span class="n">tpacket_req</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="kt">unsigned</span> <span class="kt">int</span>	<span class="n">tp_block_size</span><span class="p">;</span>	<span class="cm">/* Minimal size of contiguous block */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">unsigned</span> <span class="kt">int</span>	<span class="n">tp_block_nr</span><span class="p">;</span>	<span class="cm">/* Number of blocks */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">unsigned</span> <span class="kt">int</span>	<span class="n">tp_frame_size</span><span class="p">;</span>	<span class="cm">/* Size of frame */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">unsigned</span> <span class="kt">int</span>	<span class="n">tp_frame_nr</span><span class="p">;</span>	<span class="cm">/* Total number of frames */</span>
</span></span><span class="line"><span class="cl"><span class="p">};</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">struct</span> <span class="n">tpacket_req3</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="kt">unsigned</span> <span class="kt">int</span>	<span class="n">tp_block_size</span><span class="p">;</span>	<span class="cm">/* Minimal size of contiguous block */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">unsigned</span> <span class="kt">int</span>	<span class="n">tp_block_nr</span><span class="p">;</span>	<span class="cm">/* Number of blocks */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">unsigned</span> <span class="kt">int</span>	<span class="n">tp_frame_size</span><span class="p">;</span>	<span class="cm">/* Size of frame */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">unsigned</span> <span class="kt">int</span>	<span class="n">tp_frame_nr</span><span class="p">;</span>	<span class="cm">/* Total number of frames */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">unsigned</span> <span class="kt">int</span>	<span class="n">tp_retire_blk_tov</span><span class="p">;</span> <span class="cm">/* timeout in msecs */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">unsigned</span> <span class="kt">int</span>	<span class="n">tp_sizeof_priv</span><span class="p">;</span> <span class="cm">/* offset to private data area */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">unsigned</span> <span class="kt">int</span>	<span class="n">tp_feature_req_word</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">};</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="p">(</span><span class="n">setsockopt</span><span class="p">(</span><span class="n">handle</span><span class="o">-&gt;</span><span class="n">fd</span><span class="p">,</span> <span class="n">SOL_PACKET</span><span class="p">,</span> <span class="n">PACKET_RX_RING</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">				<span class="p">(</span><span class="kt">void</span> <span class="o">*</span><span class="p">)</span> <span class="o">&amp;</span><span class="n">req</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">req</span><span class="p">)))</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="cm">/* memory map the rx ring */</span>
</span></span><span class="line"><span class="cl"><span class="n">handlep</span><span class="o">-&gt;</span><span class="n">mmapbuflen</span> <span class="o">=</span> <span class="n">req</span><span class="p">.</span><span class="n">tp_block_nr</span> <span class="o">*</span> <span class="n">req</span><span class="p">.</span><span class="n">tp_block_size</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="n">handlep</span><span class="o">-&gt;</span><span class="n">mmapbuf</span> <span class="o">=</span> <span class="n">mmap</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">handlep</span><span class="o">-&gt;</span><span class="n">mmapbuflen</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">	<span class="n">PROT_READ</span><span class="o">|</span><span class="n">PROT_WRITE</span><span class="p">,</span> <span class="n">MAP_SHARED</span><span class="p">,</span> <span class="n">handle</span><span class="o">-&gt;</span><span class="n">fd</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="cm">/* allocate a ring for each frame header pointer*/</span>
</span></span><span class="line"><span class="cl"><span class="n">handle</span><span class="o">-&gt;</span><span class="n">cc</span> <span class="o">=</span> <span class="n">req</span><span class="p">.</span><span class="n">tp_frame_nr</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="n">handle</span><span class="o">-&gt;</span><span class="n">buffer</span> <span class="o">=</span> <span class="n">malloc</span><span class="p">(</span><span class="n">handle</span><span class="o">-&gt;</span><span class="n">cc</span> <span class="o">*</span> <span class="k">sizeof</span><span class="p">(</span><span class="k">union</span> <span class="n">thdr</span> <span class="o">*</span><span class="p">));</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="cm">/* fill the header ring with proper frame ptr*/</span>
</span></span><span class="line"><span class="cl"><span class="n">handle</span><span class="o">-&gt;</span><span class="n">offset</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="k">for</span> <span class="p">(</span><span class="n">i</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span> <span class="n">i</span><span class="o">&lt;</span><span class="n">req</span><span class="p">.</span><span class="n">tp_block_nr</span><span class="p">;</span> <span class="o">++</span><span class="n">i</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="n">u_char</span> <span class="o">*</span><span class="n">base</span> <span class="o">=</span> <span class="o">&amp;</span><span class="n">handlep</span><span class="o">-&gt;</span><span class="n">mmapbuf</span><span class="p">[</span><span class="n">i</span><span class="o">*</span><span class="n">req</span><span class="p">.</span><span class="n">tp_block_size</span><span class="p">];</span>
</span></span><span class="line"><span class="cl">	<span class="k">for</span> <span class="p">(</span><span class="n">j</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span> <span class="n">j</span><span class="o">&lt;</span><span class="n">frames_per_block</span><span class="p">;</span> <span class="o">++</span><span class="n">j</span><span class="p">,</span> <span class="o">++</span><span class="n">handle</span><span class="o">-&gt;</span><span class="n">offset</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">		<span class="n">RING_GET_CURRENT_FRAME</span><span class="p">(</span><span class="n">handle</span><span class="p">)</span> <span class="o">=</span> <span class="n">base</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">		<span class="n">base</span> <span class="o">+=</span> <span class="n">req</span><span class="p">.</span><span class="n">tp_frame_size</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">handle</span><span class="o">-&gt;</span><span class="n">bufsize</span> <span class="o">=</span> <span class="n">req</span><span class="p">.</span><span class="n">tp_frame_size</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="n">handle</span><span class="o">-&gt;</span><span class="n">offset</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="k">return</span> <span class="mi">1</span><span class="p">;</span>
</span></span></code></pre></td></tr></table>
</div>
</div><h4 id="pcap_read_linux_mmap_v3">pcap_read_linux_mmap_v3</h4>
<p>就是从内核循环收包并调用回调函数的过程</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">  1
</span><span class="lnt">  2
</span><span class="lnt">  3
</span><span class="lnt">  4
</span><span class="lnt">  5
</span><span class="lnt">  6
</span><span class="lnt">  7
</span><span class="lnt">  8
</span><span class="lnt">  9
</span><span class="lnt"> 10
</span><span class="lnt"> 11
</span><span class="lnt"> 12
</span><span class="lnt"> 13
</span><span class="lnt"> 14
</span><span class="lnt"> 15
</span><span class="lnt"> 16
</span><span class="lnt"> 17
</span><span class="lnt"> 18
</span><span class="lnt"> 19
</span><span class="lnt"> 20
</span><span class="lnt"> 21
</span><span class="lnt"> 22
</span><span class="lnt"> 23
</span><span class="lnt"> 24
</span><span class="lnt"> 25
</span><span class="lnt"> 26
</span><span class="lnt"> 27
</span><span class="lnt"> 28
</span><span class="lnt"> 29
</span><span class="lnt"> 30
</span><span class="lnt"> 31
</span><span class="lnt"> 32
</span><span class="lnt"> 33
</span><span class="lnt"> 34
</span><span class="lnt"> 35
</span><span class="lnt"> 36
</span><span class="lnt"> 37
</span><span class="lnt"> 38
</span><span class="lnt"> 39
</span><span class="lnt"> 40
</span><span class="lnt"> 41
</span><span class="lnt"> 42
</span><span class="lnt"> 43
</span><span class="lnt"> 44
</span><span class="lnt"> 45
</span><span class="lnt"> 46
</span><span class="lnt"> 47
</span><span class="lnt"> 48
</span><span class="lnt"> 49
</span><span class="lnt"> 50
</span><span class="lnt"> 51
</span><span class="lnt"> 52
</span><span class="lnt"> 53
</span><span class="lnt"> 54
</span><span class="lnt"> 55
</span><span class="lnt"> 56
</span><span class="lnt"> 57
</span><span class="lnt"> 58
</span><span class="lnt"> 59
</span><span class="lnt"> 60
</span><span class="lnt"> 61
</span><span class="lnt"> 62
</span><span class="lnt"> 63
</span><span class="lnt"> 64
</span><span class="lnt"> 65
</span><span class="lnt"> 66
</span><span class="lnt"> 67
</span><span class="lnt"> 68
</span><span class="lnt"> 69
</span><span class="lnt"> 70
</span><span class="lnt"> 71
</span><span class="lnt"> 72
</span><span class="lnt"> 73
</span><span class="lnt"> 74
</span><span class="lnt"> 75
</span><span class="lnt"> 76
</span><span class="lnt"> 77
</span><span class="lnt"> 78
</span><span class="lnt"> 79
</span><span class="lnt"> 80
</span><span class="lnt"> 81
</span><span class="lnt"> 82
</span><span class="lnt"> 83
</span><span class="lnt"> 84
</span><span class="lnt"> 85
</span><span class="lnt"> 86
</span><span class="lnt"> 87
</span><span class="lnt"> 88
</span><span class="lnt"> 89
</span><span class="lnt"> 90
</span><span class="lnt"> 91
</span><span class="lnt"> 92
</span><span class="lnt"> 93
</span><span class="lnt"> 94
</span><span class="lnt"> 95
</span><span class="lnt"> 96
</span><span class="lnt"> 97
</span><span class="lnt"> 98
</span><span class="lnt"> 99
</span><span class="lnt">100
</span><span class="lnt">101
</span><span class="lnt">102
</span><span class="lnt">103
</span><span class="lnt">104
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="line"><span class="cl"><span class="c1">// pcap-linux.c
</span></span></span><span class="line"><span class="cl"><span class="c1">// 参数跟pcap_loop完全相同 实际上pcap_loop就是readop的wrapper 往上翻可以看用法 往下翻有pcap_loop的源码
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">static</span> <span class="kt">int</span>
</span></span><span class="line"><span class="cl"><span class="nf">pcap_read_linux_mmap_v3</span><span class="p">(</span><span class="n">pcap_t</span> <span class="o">*</span><span class="n">handle</span><span class="p">,</span> <span class="kt">int</span> <span class="n">max_packets</span><span class="p">,</span> <span class="n">pcap_handler</span> <span class="n">callback</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">		<span class="n">u_char</span> <span class="o">*</span><span class="n">user</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="k">struct</span> <span class="n">pcap_linux</span> <span class="o">*</span><span class="n">handlep</span> <span class="o">=</span> <span class="n">handle</span><span class="o">-&gt;</span><span class="n">priv</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">union</span> <span class="n">thdr</span> <span class="n">h</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span> <span class="n">pkts</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span> <span class="n">ret</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nl">again</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">	<span class="n">h</span><span class="p">.</span><span class="n">raw</span> <span class="o">=</span> <span class="n">RING_GET_CURRENT_FRAME</span><span class="p">(</span><span class="n">handle</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="c1">// ...
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="cm">/* non-positive values of max_packets are used to require all
</span></span></span><span class="line"><span class="cl"><span class="cm">	 * packets currently available in the ring */</span>
</span></span><span class="line"><span class="cl">	<span class="k">while</span> <span class="p">((</span><span class="n">pkts</span> <span class="o">&lt;</span> <span class="n">max_packets</span><span class="p">)</span> <span class="o">||</span> <span class="n">PACKET_COUNT_IS_UNLIMITED</span><span class="p">(</span><span class="n">max_packets</span><span class="p">))</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">		<span class="kt">int</span> <span class="n">packets_to_read</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">		<span class="k">if</span> <span class="p">(</span><span class="n">handlep</span><span class="o">-&gt;</span><span class="n">current_packet</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">			<span class="n">h</span><span class="p">.</span><span class="n">raw</span> <span class="o">=</span> <span class="n">RING_GET_CURRENT_FRAME</span><span class="p">(</span><span class="n">handle</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">			<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">packet_mmap_v3_acquire</span><span class="p">(</span><span class="n">h</span><span class="p">.</span><span class="n">h3</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">				<span class="k">break</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">			<span class="n">handlep</span><span class="o">-&gt;</span><span class="n">current_packet</span> <span class="o">=</span> <span class="n">h</span><span class="p">.</span><span class="n">raw</span> <span class="o">+</span> <span class="n">h</span><span class="p">.</span><span class="n">h3</span><span class="o">-&gt;</span><span class="n">hdr</span><span class="p">.</span><span class="n">bh1</span><span class="p">.</span><span class="n">offset_to_first_pkt</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">			<span class="n">handlep</span><span class="o">-&gt;</span><span class="n">packets_left</span> <span class="o">=</span> <span class="n">h</span><span class="p">.</span><span class="n">h3</span><span class="o">-&gt;</span><span class="n">hdr</span><span class="p">.</span><span class="n">bh1</span><span class="p">.</span><span class="n">num_pkts</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">		<span class="p">}</span>
</span></span><span class="line"><span class="cl">		<span class="n">packets_to_read</span> <span class="o">=</span> <span class="n">handlep</span><span class="o">-&gt;</span><span class="n">packets_left</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">		<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">PACKET_COUNT_IS_UNLIMITED</span><span class="p">(</span><span class="n">max_packets</span><span class="p">)</span> <span class="o">&amp;&amp;</span>
</span></span><span class="line"><span class="cl">		    <span class="n">packets_to_read</span> <span class="o">&gt;</span> <span class="p">(</span><span class="n">max_packets</span> <span class="o">-</span> <span class="n">pkts</span><span class="p">))</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">			<span class="cm">/*
</span></span></span><span class="line"><span class="cl"><span class="cm">			 * We&#39;ve been given a maximum number of packets
</span></span></span><span class="line"><span class="cl"><span class="cm">			 * to process, and there are more packets in
</span></span></span><span class="line"><span class="cl"><span class="cm">			 * this buffer than that.  Only process enough
</span></span></span><span class="line"><span class="cl"><span class="cm">			 * of them to get us up to that maximum.
</span></span></span><span class="line"><span class="cl"><span class="cm">			 */</span>
</span></span><span class="line"><span class="cl">			<span class="n">packets_to_read</span> <span class="o">=</span> <span class="n">max_packets</span> <span class="o">-</span> <span class="n">pkts</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">		<span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">		<span class="k">while</span> <span class="p">(</span><span class="n">packets_to_read</span><span class="o">--</span> <span class="o">&amp;&amp;</span> <span class="o">!</span><span class="n">handle</span><span class="o">-&gt;</span><span class="n">break_loop</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">			<span class="k">struct</span> <span class="n">tpacket3_hdr</span><span class="o">*</span> <span class="n">tp3_hdr</span> <span class="o">=</span> <span class="p">(</span><span class="k">struct</span> <span class="n">tpacket3_hdr</span><span class="o">*</span><span class="p">)</span> <span class="n">handlep</span><span class="o">-&gt;</span><span class="n">current_packet</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">			<span class="n">ret</span> <span class="o">=</span> <span class="n">pcap_handle_packet_mmap</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">					<span class="n">handle</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">					<span class="n">callback</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">					<span class="n">user</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">					<span class="n">handlep</span><span class="o">-&gt;</span><span class="n">current_packet</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">					<span class="n">tp3_hdr</span><span class="o">-&gt;</span><span class="n">tp_len</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">					<span class="n">tp3_hdr</span><span class="o">-&gt;</span><span class="n">tp_mac</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">					<span class="n">tp3_hdr</span><span class="o">-&gt;</span><span class="n">tp_snaplen</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">					<span class="n">tp3_hdr</span><span class="o">-&gt;</span><span class="n">tp_sec</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">					<span class="n">handle</span><span class="o">-&gt;</span><span class="n">opt</span><span class="p">.</span><span class="n">tstamp_precision</span> <span class="o">==</span> <span class="n">PCAP_TSTAMP_PRECISION_NANO</span> <span class="o">?</span> <span class="n">tp3_hdr</span><span class="o">-&gt;</span><span class="nl">tp_nsec</span> <span class="p">:</span> <span class="n">tp3_hdr</span><span class="o">-&gt;</span><span class="n">tp_nsec</span> <span class="o">/</span> <span class="mi">1000</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">					<span class="n">VLAN_VALID</span><span class="p">(</span><span class="n">tp3_hdr</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">tp3_hdr</span><span class="o">-&gt;</span><span class="n">hv1</span><span class="p">),</span>
</span></span><span class="line"><span class="cl">					<span class="n">tp3_hdr</span><span class="o">-&gt;</span><span class="n">hv1</span><span class="p">.</span><span class="n">tp_vlan_tci</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">					<span class="n">VLAN_TPID</span><span class="p">(</span><span class="n">tp3_hdr</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">tp3_hdr</span><span class="o">-&gt;</span><span class="n">hv1</span><span class="p">));</span>
</span></span><span class="line"><span class="cl">			<span class="k">if</span> <span class="p">(</span><span class="n">ret</span> <span class="o">==</span> <span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">				<span class="n">pkts</span><span class="o">++</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">			<span class="p">}</span> <span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="n">ret</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">				<span class="n">handlep</span><span class="o">-&gt;</span><span class="n">current_packet</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">				<span class="k">return</span> <span class="n">ret</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">			<span class="p">}</span>
</span></span><span class="line"><span class="cl">			<span class="n">handlep</span><span class="o">-&gt;</span><span class="n">current_packet</span> <span class="o">+=</span> <span class="n">tp3_hdr</span><span class="o">-&gt;</span><span class="n">tp_next_offset</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">			<span class="n">handlep</span><span class="o">-&gt;</span><span class="n">packets_left</span><span class="o">--</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">		<span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">		<span class="k">if</span> <span class="p">(</span><span class="n">handlep</span><span class="o">-&gt;</span><span class="n">packets_left</span> <span class="o">&lt;=</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">			<span class="cm">/*
</span></span></span><span class="line"><span class="cl"><span class="cm">			 * Hand this block back to the kernel, and, if
</span></span></span><span class="line"><span class="cl"><span class="cm">			 * we&#39;re counting blocks that need to be
</span></span></span><span class="line"><span class="cl"><span class="cm">			 * filtered in userland after having been
</span></span></span><span class="line"><span class="cl"><span class="cm">			 * filtered by the kernel, count the one we&#39;ve
</span></span></span><span class="line"><span class="cl"><span class="cm">			 * just processed.
</span></span></span><span class="line"><span class="cl"><span class="cm">			 */</span>
</span></span><span class="line"><span class="cl">			<span class="n">packet_mmap_v3_release</span><span class="p">(</span><span class="n">h</span><span class="p">.</span><span class="n">h3</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">			<span class="k">if</span> <span class="p">(</span><span class="n">handlep</span><span class="o">-&gt;</span><span class="n">blocks_to_filter_in_userland</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">				<span class="n">handlep</span><span class="o">-&gt;</span><span class="n">blocks_to_filter_in_userland</span><span class="o">--</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">				<span class="k">if</span> <span class="p">(</span><span class="n">handlep</span><span class="o">-&gt;</span><span class="n">blocks_to_filter_in_userland</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">					<span class="cm">/*
</span></span></span><span class="line"><span class="cl"><span class="cm">					 * No more blocks need to be filtered
</span></span></span><span class="line"><span class="cl"><span class="cm">					 * in userland.
</span></span></span><span class="line"><span class="cl"><span class="cm">					 */</span>
</span></span><span class="line"><span class="cl">					<span class="n">handlep</span><span class="o">-&gt;</span><span class="n">filter_in_userland</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">				<span class="p">}</span>
</span></span><span class="line"><span class="cl">			<span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">			<span class="cm">/* next block */</span>
</span></span><span class="line"><span class="cl">			<span class="k">if</span> <span class="p">(</span><span class="o">++</span><span class="n">handle</span><span class="o">-&gt;</span><span class="n">offset</span> <span class="o">&gt;=</span> <span class="n">handle</span><span class="o">-&gt;</span><span class="n">cc</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">				<span class="n">handle</span><span class="o">-&gt;</span><span class="n">offset</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">			<span class="n">handlep</span><span class="o">-&gt;</span><span class="n">current_packet</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">		<span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">		<span class="cm">/* check for break loop condition*/</span>
</span></span><span class="line"><span class="cl">		<span class="k">if</span> <span class="p">(</span><span class="n">handle</span><span class="o">-&gt;</span><span class="n">break_loop</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">			<span class="n">handle</span><span class="o">-&gt;</span><span class="n">break_loop</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">			<span class="k">return</span> <span class="n">PCAP_ERROR_BREAK</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">		<span class="p">}</span>
</span></span><span class="line"><span class="cl">	<span class="p">}</span>
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">pkts</span> <span class="o">==</span> <span class="mi">0</span> <span class="o">&amp;&amp;</span> <span class="n">handlep</span><span class="o">-&gt;</span><span class="n">timeout</span> <span class="o">==</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">		<span class="cm">/* Block until we see a packet. */</span>
</span></span><span class="line"><span class="cl">		<span class="k">goto</span> <span class="n">again</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="p">}</span>
</span></span><span class="line"><span class="cl">	<span class="k">return</span> <span class="n">pkts</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>pcap_wait_for_frames_mmap-&gt;poll</p>
<h2 id="pcap_compilepcap_setfilter">pcap_compile&amp;&amp;pcap_setfilter</h2>
<p>pcap_compile中涉及词法分析等编译原理内容,十分复杂(代码量是核心部分两倍),暂时不深入研究</p>
<p>此处可通过tcpdump的-d参数以类汇编指令输出编译的packet-matching code</p>
<p>官方解释:Dump the compiled packet-matching code in a human readable form to standard output and stop.</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">&gt; sudo tcpdump host 192.168.142.1 -d
</span></span><span class="line"><span class="cl"><span class="o">(</span>000<span class="o">)</span> ldh      <span class="o">[</span>12<span class="o">]</span>
</span></span><span class="line"><span class="cl"><span class="o">(</span>001<span class="o">)</span> jeq      <span class="c1">#0x800           jt 2    jf 6</span>
</span></span><span class="line"><span class="cl"><span class="o">(</span>002<span class="o">)</span> ld       <span class="o">[</span>26<span class="o">]</span>
</span></span><span class="line"><span class="cl"><span class="o">(</span>003<span class="o">)</span> jeq      <span class="c1">#0xc0a88e01      jt 12   jf 4</span>
</span></span><span class="line"><span class="cl"><span class="o">(</span>004<span class="o">)</span> ld       <span class="o">[</span>30<span class="o">]</span>
</span></span><span class="line"><span class="cl"><span class="o">(</span>005<span class="o">)</span> jeq      <span class="c1">#0xc0a88e01      jt 12   jf 13</span>
</span></span><span class="line"><span class="cl"><span class="o">(</span>006<span class="o">)</span> jeq      <span class="c1">#0x806           jt 8    jf 7</span>
</span></span><span class="line"><span class="cl"><span class="o">(</span>007<span class="o">)</span> jeq      <span class="c1">#0x8035          jt 8    jf 13</span>
</span></span><span class="line"><span class="cl"><span class="o">(</span>008<span class="o">)</span> ld       <span class="o">[</span>28<span class="o">]</span>
</span></span><span class="line"><span class="cl"><span class="o">(</span>009<span class="o">)</span> jeq      <span class="c1">#0xc0a88e01      jt 12   jf 10</span>
</span></span><span class="line"><span class="cl"><span class="o">(</span>010<span class="o">)</span> ld       <span class="o">[</span>38<span class="o">]</span>
</span></span><span class="line"><span class="cl"><span class="o">(</span>011<span class="o">)</span> jeq      <span class="c1">#0xc0a88e01      jt 12   jf 13</span>
</span></span><span class="line"><span class="cl"><span class="o">(</span>012<span class="o">)</span> ret      <span class="c1">#262144</span>
</span></span><span class="line"><span class="cl"><span class="o">(</span>013<span class="o">)</span> ret      <span class="c1">#0</span>
</span></span></code></pre></td></tr></table>
</div>
</div><pre tabindex="0"><code>jeq = judge equal
jt = judge true
jf = judge false
ld = load?
上方一共14行代码
(000)跳到12字节处
// PS:以太网头目标MAC6字节 源MAC字节
(001)判断是否等于0x800 等于跳到(002) 不等跳到(006)
// PS:此处0x800代表的是IPv4
(002)跳转到26字节
// PS:以太网帧14字节(12字节MAC+2字节Type),IPv4头20字节 最后8字节为源地址和目标地址 26=14+20-8 也就是跳到源地址的地方
(003)继续往下执行 此处判断是否等于0xc0a88e01 相等跳到(012) 不等跳到(0004)
// PS:0xc0a88e01就是tcpdump命令中输入地址192.168.142.1的十六进制表示 此处判断源地址是否为指定地址,是的话就跳到(012)直接ret
(004)跳到30字节处
// PS:如果源地址不是我们指定的地址就跳到(004),同刚才源地址的计算30=14+20-4
(005)判断是否为指定的ip 是的话跳到(012) 不是的话跳到(013)
// PS:也就是说如果不是源地址就判断是不是目标地址 是的话就ret #262144
(006)判断是否等于0x806 等于跳到(008) 不等跳到(007)
// PS:不等于0x800后跳转到此处继续判断是否等于0x806 0x806表示的是ARP协议
(007)判断是否等于0x8035 等于跳转(008) 不等跳转(013)
// PS:
(008)跳转到28字节处
// PS:ARP协议头为28字节,最后为6字节源Mac 4字节源ip 6字节目标Mac 4字节目标ip,28=14+28-(4+6+4) 也就是跳到源ip处
(009)判断是否为指定ip 是跳转(012) 不是跳转(010)
// PS: 判断ARP协议的源ip是否为我们指定ip 
(010)跳转到38字节处
// PS:同上方arp源ip偏移计算此处38=14+28-4 
(011)判断是否为只当ip 是挑战(012) 不是跳转(013)
// PS:即判断目标ip是否为指定ip
(012) ret #262144
(013) ret #0
</code></pre><p>pcap_setfilter调用链,最终调用setsockopt通知内核启用过滤</p>
<pre tabindex="0"><code>pcap_setfilter-&gt;pcap_setfilter_linux-&gt;set_kernel_filter-&gt;setsockopt
setsockopt(handle-&gt;fd, SOL_SOCKET, SO_ATTACH_FILTER, 
			&amp;total_fcode, sizeof(total_fcode))
</code></pre><h2 id="pcap_loop">pcap_loop</h2>
<p>pcap_loop的逻辑十分简单,如果p-&gt;rfile不为空就存入文件,否则调用p-&gt;read_op()</p>
<p>而我们的read_op()是在pcap_activate_linux()中根据版本设置的函数指针pcap_read_linux_mmap_v3/pcap_read_linux_mmap_v2</p>
<p>(网上看其他人对老版本的源码分析pcap_loop中还是不断recvfrom来循环收包)</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="line"><span class="cl"><span class="kt">int</span> <span class="nf">pcap_loop</span><span class="p">(</span><span class="n">pcap_t</span> <span class="o">*</span><span class="n">p</span><span class="p">,</span> <span class="kt">int</span> <span class="n">cnt</span><span class="p">,</span> <span class="n">pcap_handler</span> <span class="n">callback</span><span class="p">,</span> <span class="n">u_char</span> <span class="o">*</span><span class="n">user</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="k">register</span> <span class="kt">int</span> <span class="n">n</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="k">for</span> <span class="p">(;;)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">		<span class="k">if</span> <span class="p">(</span><span class="n">p</span><span class="o">-&gt;</span><span class="n">rfile</span> <span class="o">!=</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">			<span class="c1">// 0 means EOF, so don&#39;t loop if we get 0.
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>			<span class="n">n</span> <span class="o">=</span> <span class="n">pcap_offline_read</span><span class="p">(</span><span class="n">p</span><span class="p">,</span> <span class="n">cnt</span><span class="p">,</span> <span class="n">callback</span><span class="p">,</span> <span class="n">user</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">		<span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">			<span class="k">do</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">				<span class="n">n</span> <span class="o">=</span> <span class="n">p</span><span class="o">-&gt;</span><span class="n">read_op</span><span class="p">(</span><span class="n">p</span><span class="p">,</span> <span class="n">cnt</span><span class="p">,</span> <span class="n">callback</span><span class="p">,</span> <span class="n">user</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">			<span class="p">}</span> <span class="k">while</span> <span class="p">(</span><span class="n">n</span> <span class="o">==</span> <span class="mi">0</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">		<span class="p">}</span>
</span></span><span class="line"><span class="cl">	<span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><h2 id="kernelnet结构体">kernel/net结构体</h2>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span><span class="lnt">37
</span><span class="lnt">38
</span><span class="lnt">39
</span><span class="lnt">40
</span><span class="lnt">41
</span><span class="lnt">42
</span><span class="lnt">43
</span><span class="lnt">44
</span><span class="lnt">45
</span><span class="lnt">46
</span><span class="lnt">47
</span><span class="lnt">48
</span><span class="lnt">49
</span><span class="lnt">50
</span><span class="lnt">51
</span><span class="lnt">52
</span><span class="lnt">53
</span><span class="lnt">54
</span><span class="lnt">55
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="line"><span class="cl"><span class="c1">// include/net/sock.h
</span></span></span><span class="line"><span class="cl"><span class="c1">// 网络层套接字 network layer representation of sockets
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">struct</span> <span class="n">sock</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="c1">// net/packet/internal.h
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">struct</span> <span class="n">packet_sock</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="cm">/* struct sock has to be the first member of packet_sock */</span>
</span></span><span class="line"><span class="cl">	<span class="k">struct</span> <span class="n">sock</span>		<span class="n">sk</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">struct</span> <span class="n">packet_fanout</span>	<span class="o">*</span><span class="n">fanout</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">union</span>  <span class="n">tpacket_stats_u</span>	<span class="n">stats</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">struct</span> <span class="n">packet_ring_buffer</span>	<span class="n">rx_ring</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">struct</span> <span class="n">packet_ring_buffer</span>	<span class="n">tx_ring</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span>			<span class="n">copy_thresh</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">spinlock_t</span>		<span class="n">bind_lock</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">struct</span> <span class="n">mutex</span>		<span class="n">pg_vec_lock</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">unsigned</span> <span class="kt">int</span>		<span class="n">running</span><span class="p">;</span>	<span class="cm">/* bind_lock must be held */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">unsigned</span> <span class="kt">int</span>		<span class="nl">auxdata</span><span class="p">:</span><span class="mi">1</span><span class="p">,</span>	<span class="cm">/* writer must hold sock lock */</span>
</span></span><span class="line"><span class="cl">				<span class="nl">origdev</span><span class="p">:</span><span class="mi">1</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">				<span class="nl">has_vnet_hdr</span><span class="p">:</span><span class="mi">1</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">				<span class="nl">tp_loss</span><span class="p">:</span><span class="mi">1</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">				<span class="nl">tp_tx_has_off</span><span class="p">:</span><span class="mi">1</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span>			<span class="n">pressure</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span>			<span class="n">ifindex</span><span class="p">;</span>	<span class="cm">/* bound device		*/</span>
</span></span><span class="line"><span class="cl">	<span class="n">__be16</span>			<span class="n">num</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">struct</span> <span class="n">packet_rollover</span>	<span class="o">*</span><span class="n">rollover</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">struct</span> <span class="n">packet_mclist</span>	<span class="o">*</span><span class="n">mclist</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">atomic_t</span>		<span class="n">mapped</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">enum</span> <span class="n">tpacket_versions</span>	<span class="n">tp_version</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">unsigned</span> <span class="kt">int</span>		<span class="n">tp_hdrlen</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">unsigned</span> <span class="kt">int</span>		<span class="n">tp_reserve</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">unsigned</span> <span class="kt">int</span>		<span class="n">tp_tstamp</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">struct</span> <span class="n">completion</span>	<span class="n">skb_completion</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">struct</span> <span class="n">net_device</span> <span class="n">__rcu</span>	<span class="o">*</span><span class="n">cached_dev</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span>			<span class="p">(</span><span class="o">*</span><span class="n">xmit</span><span class="p">)(</span><span class="k">struct</span> <span class="n">sk_buff</span> <span class="o">*</span><span class="n">skb</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="k">struct</span> <span class="n">packet_type</span>	<span class="n">prot_hook</span> <span class="n">____cacheline_aligned_in_smp</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">atomic_t</span>		<span class="n">tp_drops</span> <span class="n">____cacheline_aligned_in_smp</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">};</span>
</span></span><span class="line"><span class="cl"><span class="c1">// include/linux/netdevice.h
</span></span></span><span class="line"><span class="cl"><span class="c1"></span><span class="k">struct</span> <span class="n">packet_type</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="n">__be16</span>			<span class="n">type</span><span class="p">;</span>	<span class="cm">/* This is really htons(ether_type). */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">bool</span>			<span class="n">ignore_outgoing</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">struct</span> <span class="n">net_device</span>	<span class="o">*</span><span class="n">dev</span><span class="p">;</span>	<span class="cm">/* NULL is wildcarded here	     */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span>			<span class="p">(</span><span class="o">*</span><span class="n">func</span><span class="p">)</span> <span class="p">(</span><span class="k">struct</span> <span class="n">sk_buff</span> <span class="o">*</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">					 <span class="k">struct</span> <span class="n">net_device</span> <span class="o">*</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">					 <span class="k">struct</span> <span class="n">packet_type</span> <span class="o">*</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">					 <span class="k">struct</span> <span class="n">net_device</span> <span class="o">*</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="kt">void</span>			<span class="p">(</span><span class="o">*</span><span class="n">list_func</span><span class="p">)</span> <span class="p">(</span><span class="k">struct</span> <span class="n">list_head</span> <span class="o">*</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">					      <span class="k">struct</span> <span class="n">packet_type</span> <span class="o">*</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">					      <span class="k">struct</span> <span class="n">net_device</span> <span class="o">*</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="kt">bool</span>			<span class="p">(</span><span class="o">*</span><span class="n">id_match</span><span class="p">)(</span><span class="k">struct</span> <span class="n">packet_type</span> <span class="o">*</span><span class="n">ptype</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">					    <span class="k">struct</span> <span class="n">sock</span> <span class="o">*</span><span class="n">sk</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="kt">void</span>			<span class="o">*</span><span class="n">af_packet_priv</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">struct</span> <span class="n">list_head</span>	<span class="n">list</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">};</span>
</span></span></code></pre></td></tr></table>
</div>
</div><h2 id="kernelnet-源码">kernel/net 源码</h2>
<h3 id="netpacketaf_packetcpacket_init">net/packet/af_packet.c/packet_init</h3>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="line"><span class="cl"><span class="k">static</span> <span class="kt">int</span> <span class="n">__init</span> <span class="nf">packet_init</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span> <span class="n">rc</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">rc</span> <span class="o">=</span> <span class="n">proto_register</span><span class="p">(</span><span class="o">&amp;</span><span class="n">packet_proto</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">rc</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">		<span class="k">goto</span> <span class="n">out</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">rc</span> <span class="o">=</span> <span class="n">sock_register</span><span class="p">(</span><span class="o">&amp;</span><span class="n">packet_family_ops</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">rc</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">		<span class="k">goto</span> <span class="n">out_proto</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">rc</span> <span class="o">=</span> <span class="n">register_pernet_subsys</span><span class="p">(</span><span class="o">&amp;</span><span class="n">packet_net_ops</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">rc</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">		<span class="k">goto</span> <span class="n">out_sock</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">rc</span> <span class="o">=</span> <span class="n">register_netdevice_notifier</span><span class="p">(</span><span class="o">&amp;</span><span class="n">packet_netdev_notifier</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">rc</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">		<span class="k">goto</span> <span class="n">out_pernet</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nl">out_pernet</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">	<span class="n">unregister_pernet_subsys</span><span class="p">(</span><span class="o">&amp;</span><span class="n">packet_net_ops</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="nl">out_sock</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">	<span class="n">sock_unregister</span><span class="p">(</span><span class="n">PF_PACKET</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="nl">out_proto</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">	<span class="n">proto_unregister</span><span class="p">(</span><span class="o">&amp;</span><span class="n">packet_proto</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="nl">out</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">	<span class="k">return</span> <span class="n">rc</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">module_exit</span><span class="p">(</span><span class="n">packet_exit</span><span class="p">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>module_init模块初始化 程序运行的时候会自动调用packet_init初始化模块</p>
<p>sock_register 本质是将 struct net_proto_family packet_family_ops 注册到socket.c一个全局的 *net_families[NPROTO] 变量中</p>
<h3 id="netsocketc">net/socket.c</h3>
<p>系统通过socket()建立通信</p>
<p>socket() 本质上是调用了 sock_create() 函数并用sock_map_fd()将socket绑定到文件描述符上</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span><span class="lnt">37
</span><span class="lnt">38
</span><span class="lnt">39
</span><span class="lnt">40
</span><span class="lnt">41
</span><span class="lnt">42
</span><span class="lnt">43
</span><span class="lnt">44
</span><span class="lnt">45
</span><span class="lnt">46
</span><span class="lnt">47
</span><span class="lnt">48
</span><span class="lnt">49
</span><span class="lnt">50
</span><span class="lnt">51
</span><span class="lnt">52
</span><span class="lnt">53
</span><span class="lnt">54
</span><span class="lnt">55
</span><span class="lnt">56
</span><span class="lnt">57
</span><span class="lnt">58
</span><span class="lnt">59
</span><span class="lnt">60
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-C" data-lang="C"><span class="line"><span class="cl"><span class="kt">int</span> <span class="nf">__sock_create</span><span class="p">(</span><span class="k">struct</span> <span class="n">net</span> <span class="o">*</span><span class="n">net</span><span class="p">,</span> <span class="kt">int</span> <span class="n">family</span><span class="p">,</span> <span class="kt">int</span> <span class="n">type</span><span class="p">,</span> <span class="kt">int</span> <span class="n">protocol</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">			 <span class="k">struct</span> <span class="n">socket</span> <span class="o">**</span><span class="n">res</span><span class="p">,</span> <span class="kt">int</span> <span class="n">kern</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span> <span class="n">err</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">struct</span> <span class="n">socket</span> <span class="o">*</span><span class="n">sock</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">const</span> <span class="k">struct</span> <span class="n">net_proto_family</span> <span class="o">*</span><span class="n">pf</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="p">......</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="cp">#ifdef CONFIG_MODULES
</span></span></span><span class="line"><span class="cl"><span class="cp"></span>	<span class="cm">/* Attempt to load a protocol module if the find failed.
</span></span></span><span class="line"><span class="cl"><span class="cm">	 *
</span></span></span><span class="line"><span class="cl"><span class="cm">	 * 12/09/1996 Marcin: But! this makes REALLY only sense, if the user
</span></span></span><span class="line"><span class="cl"><span class="cm">	 * requested real, full-featured networking support upon configuration.
</span></span></span><span class="line"><span class="cl"><span class="cm">	 * Otherwise module support will break!
</span></span></span><span class="line"><span class="cl"><span class="cm">	 */</span>
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">rcu_access_pointer</span><span class="p">(</span><span class="n">net_families</span><span class="p">[</span><span class="n">family</span><span class="p">])</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">		<span class="n">request_module</span><span class="p">(</span><span class="s">&#34;net-pf-%d&#34;</span><span class="p">,</span> <span class="n">family</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="cp">#endif
</span></span></span><span class="line"><span class="cl"><span class="cp"></span>
</span></span><span class="line"><span class="cl">	<span class="n">rcu_read_lock</span><span class="p">();</span>
</span></span><span class="line"><span class="cl">	<span class="n">pf</span> <span class="o">=</span> <span class="n">rcu_dereference</span><span class="p">(</span><span class="n">net_families</span><span class="p">[</span><span class="n">family</span><span class="p">]);</span>
</span></span><span class="line"><span class="cl">	<span class="n">err</span> <span class="o">=</span> <span class="o">-</span><span class="n">EAFNOSUPPORT</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">pf</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">		<span class="k">goto</span> <span class="n">out_release</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="cm">/*
</span></span></span><span class="line"><span class="cl"><span class="cm">	 * We will call the -&gt;create function, that possibly is in a loadable
</span></span></span><span class="line"><span class="cl"><span class="cm">	 * module, so we have to bump that loadable module refcnt first.
</span></span></span><span class="line"><span class="cl"><span class="cm">	 */</span>
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">try_module_get</span><span class="p">(</span><span class="n">pf</span><span class="o">-&gt;</span><span class="n">owner</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">		<span class="k">goto</span> <span class="n">out_release</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="cm">/* Now protected by module ref count */</span>
</span></span><span class="line"><span class="cl">	<span class="n">rcu_read_unlock</span><span class="p">();</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">err</span> <span class="o">=</span> <span class="n">pf</span><span class="o">-&gt;</span><span class="n">create</span><span class="p">(</span><span class="n">net</span><span class="p">,</span> <span class="n">sock</span><span class="p">,</span> <span class="n">protocol</span><span class="p">,</span> <span class="n">kern</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">err</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">		<span class="k">goto</span> <span class="n">out_module_put</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="p">......</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="o">*</span><span class="n">res</span> <span class="o">=</span> <span class="n">sock</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nl">out_module_busy</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">	<span class="n">err</span> <span class="o">=</span> <span class="o">-</span><span class="n">EAFNOSUPPORT</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="nl">out_module_put</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">	<span class="n">sock</span><span class="o">-&gt;</span><span class="n">ops</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">module_put</span><span class="p">(</span><span class="n">pf</span><span class="o">-&gt;</span><span class="n">owner</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="nl">out_sock_release</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">	<span class="n">sock_release</span><span class="p">(</span><span class="n">sock</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="k">return</span> <span class="n">err</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nl">out_release</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">	<span class="n">rcu_read_unlock</span><span class="p">();</span>
</span></span><span class="line"><span class="cl">	<span class="k">goto</span> <span class="n">out_sock_release</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="n">EXPORT_SYMBOL</span><span class="p">(</span><span class="n">__sock_create</span><span class="p">);</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>这里通过pf-&gt;create(net, sock, protocol, kern); 调用之前pf_packet init时绑定到 net_families[family]的create方法即: packet_create</p>
<h3 id="netpacketaf_packetcpacket_create">net/packet/af_packet.c/packet_create</h3>
<p>如注释所写，这个函数Create a packet of type SOCK_PACKET.</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span><span class="lnt">16
</span><span class="lnt">17
</span><span class="lnt">18
</span><span class="lnt">19
</span><span class="lnt">20
</span><span class="lnt">21
</span><span class="lnt">22
</span><span class="lnt">23
</span><span class="lnt">24
</span><span class="lnt">25
</span><span class="lnt">26
</span><span class="lnt">27
</span><span class="lnt">28
</span><span class="lnt">29
</span><span class="lnt">30
</span><span class="lnt">31
</span><span class="lnt">32
</span><span class="lnt">33
</span><span class="lnt">34
</span><span class="lnt">35
</span><span class="lnt">36
</span><span class="lnt">37
</span><span class="lnt">38
</span><span class="lnt">39
</span><span class="lnt">40
</span><span class="lnt">41
</span><span class="lnt">42
</span><span class="lnt">43
</span><span class="lnt">44
</span><span class="lnt">45
</span><span class="lnt">46
</span><span class="lnt">47
</span><span class="lnt">48
</span><span class="lnt">49
</span><span class="lnt">50
</span><span class="lnt">51
</span><span class="lnt">52
</span><span class="lnt">53
</span><span class="lnt">54
</span><span class="lnt">55
</span><span class="lnt">56
</span><span class="lnt">57
</span><span class="lnt">58
</span><span class="lnt">59
</span><span class="lnt">60
</span><span class="lnt">61
</span><span class="lnt">62
</span><span class="lnt">63
</span><span class="lnt">64
</span><span class="lnt">65
</span><span class="lnt">66
</span><span class="lnt">67
</span><span class="lnt">68
</span><span class="lnt">69
</span><span class="lnt">70
</span><span class="lnt">71
</span><span class="lnt">72
</span><span class="lnt">73
</span><span class="lnt">74
</span><span class="lnt">75
</span><span class="lnt">76
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="line"><span class="cl"><span class="k">static</span> <span class="kt">int</span> <span class="nf">packet_create</span><span class="p">(</span><span class="k">struct</span> <span class="n">net</span> <span class="o">*</span><span class="n">net</span><span class="p">,</span> <span class="k">struct</span> <span class="n">socket</span> <span class="o">*</span><span class="n">sock</span><span class="p">,</span> <span class="kt">int</span> <span class="n">protocol</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">			 <span class="kt">int</span> <span class="n">kern</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="k">struct</span> <span class="n">sock</span> <span class="o">*</span><span class="n">sk</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">struct</span> <span class="n">packet_sock</span> <span class="o">*</span><span class="n">po</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">__be16</span> <span class="n">proto</span> <span class="o">=</span> <span class="p">(</span><span class="n">__force</span> <span class="n">__be16</span><span class="p">)</span><span class="n">protocol</span><span class="p">;</span> <span class="cm">/* weird, but documented */</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span> <span class="n">err</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">ns_capable</span><span class="p">(</span><span class="n">net</span><span class="o">-&gt;</span><span class="n">user_ns</span><span class="p">,</span> <span class="n">CAP_NET_RAW</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">		<span class="k">return</span> <span class="o">-</span><span class="n">EPERM</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">sock</span><span class="o">-&gt;</span><span class="n">type</span> <span class="o">!=</span> <span class="n">SOCK_DGRAM</span> <span class="o">&amp;&amp;</span> <span class="n">sock</span><span class="o">-&gt;</span><span class="n">type</span> <span class="o">!=</span> <span class="n">SOCK_RAW</span> <span class="o">&amp;&amp;</span>
</span></span><span class="line"><span class="cl">	    <span class="n">sock</span><span class="o">-&gt;</span><span class="n">type</span> <span class="o">!=</span> <span class="n">SOCK_PACKET</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">		<span class="k">return</span> <span class="o">-</span><span class="n">ESOCKTNOSUPPORT</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">sock</span><span class="o">-&gt;</span><span class="n">state</span> <span class="o">=</span> <span class="n">SS_UNCONNECTED</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">err</span> <span class="o">=</span> <span class="o">-</span><span class="n">ENOBUFS</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">sk</span> <span class="o">=</span> <span class="n">sk_alloc</span><span class="p">(</span><span class="n">net</span><span class="p">,</span> <span class="n">PF_PACKET</span><span class="p">,</span> <span class="n">GFP_KERNEL</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">packet_proto</span><span class="p">,</span> <span class="n">kern</span><span class="p">);</span>		<span class="c1">// 创建socket
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="k">if</span> <span class="p">(</span><span class="n">sk</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">		<span class="k">goto</span> <span class="n">out</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">sock</span><span class="o">-&gt;</span><span class="n">ops</span> <span class="o">=</span> <span class="o">&amp;</span><span class="n">packet_ops</span><span class="p">;</span>	<span class="c1">// 设置一系列操作函数
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="k">if</span> <span class="p">(</span><span class="n">sock</span><span class="o">-&gt;</span><span class="n">type</span> <span class="o">==</span> <span class="n">SOCK_PACKET</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">		<span class="n">sock</span><span class="o">-&gt;</span><span class="n">ops</span> <span class="o">=</span> <span class="o">&amp;</span><span class="n">packet_ops_spkt</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">sock_init_data</span><span class="p">(</span><span class="n">sock</span><span class="p">,</span> <span class="n">sk</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="c1">// 将sock结构体sk设置到packet_sock结构体po中 (struct sock has to be the first member of packet_sock)
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="n">po</span> <span class="o">=</span> <span class="n">pkt_sk</span><span class="p">(</span><span class="n">sk</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="n">init_completion</span><span class="p">(</span><span class="o">&amp;</span><span class="n">po</span><span class="o">-&gt;</span><span class="n">skb_completion</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="n">sk</span><span class="o">-&gt;</span><span class="n">sk_family</span> <span class="o">=</span> <span class="n">PF_PACKET</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">po</span><span class="o">-&gt;</span><span class="n">num</span> <span class="o">=</span> <span class="n">proto</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">po</span><span class="o">-&gt;</span><span class="n">xmit</span> <span class="o">=</span> <span class="n">dev_queue_xmit</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">err</span> <span class="o">=</span> <span class="n">packet_alloc_pending</span><span class="p">(</span><span class="n">po</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">err</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">		<span class="k">goto</span> <span class="n">out2</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">packet_cached_dev_reset</span><span class="p">(</span><span class="n">po</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">sk</span><span class="o">-&gt;</span><span class="n">sk_destruct</span> <span class="o">=</span> <span class="n">packet_sock_destruct</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">sk_refcnt_debug_inc</span><span class="p">(</span><span class="n">sk</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="cm">/*
</span></span></span><span class="line"><span class="cl"><span class="cm">	 *	Attach a protocol block
</span></span></span><span class="line"><span class="cl"><span class="cm">	 */</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">spin_lock_init</span><span class="p">(</span><span class="o">&amp;</span><span class="n">po</span><span class="o">-&gt;</span><span class="n">bind_lock</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="n">mutex_init</span><span class="p">(</span><span class="o">&amp;</span><span class="n">po</span><span class="o">-&gt;</span><span class="n">pg_vec_lock</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="n">po</span><span class="o">-&gt;</span><span class="n">rollover</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">po</span><span class="o">-&gt;</span><span class="n">prot_hook</span><span class="p">.</span><span class="n">func</span> <span class="o">=</span> <span class="n">packet_rcv</span><span class="p">;</span>	<span class="c1">// packet_type 结构体(packet_sock结构体中prot_hook是packet_type类型) 注册的处理函数 packet_rcv
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">sock</span><span class="o">-&gt;</span><span class="n">type</span> <span class="o">==</span> <span class="n">SOCK_PACKET</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">		<span class="n">po</span><span class="o">-&gt;</span><span class="n">prot_hook</span><span class="p">.</span><span class="n">func</span> <span class="o">=</span> <span class="n">packet_rcv_spkt</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">po</span><span class="o">-&gt;</span><span class="n">prot_hook</span><span class="p">.</span><span class="n">af_packet_priv</span> <span class="o">=</span> <span class="n">sk</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">proto</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">		<span class="n">po</span><span class="o">-&gt;</span><span class="n">prot_hook</span><span class="p">.</span><span class="n">type</span> <span class="o">=</span> <span class="n">proto</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">		<span class="n">__register_prot_hook</span><span class="p">(</span><span class="n">sk</span><span class="p">);</span>	<span class="c1">// 调用 net/core/dev.c/dev_add_pack()  添加到内核 ptype_all 链表上(kernel lists)
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">mutex_lock</span><span class="p">(</span><span class="o">&amp;</span><span class="n">net</span><span class="o">-&gt;</span><span class="n">packet</span><span class="p">.</span><span class="n">sklist_lock</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="n">sk_add_node_tail_rcu</span><span class="p">(</span><span class="n">sk</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">net</span><span class="o">-&gt;</span><span class="n">packet</span><span class="p">.</span><span class="n">sklist</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="n">mutex_unlock</span><span class="p">(</span><span class="o">&amp;</span><span class="n">net</span><span class="o">-&gt;</span><span class="n">packet</span><span class="p">.</span><span class="n">sklist_lock</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">preempt_disable</span><span class="p">();</span>
</span></span><span class="line"><span class="cl">	<span class="n">sock_prot_inuse_add</span><span class="p">(</span><span class="n">net</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">packet_proto</span><span class="p">,</span> <span class="mi">1</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="n">preempt_enable</span><span class="p">();</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="nl">out2</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">	<span class="n">sk_free</span><span class="p">(</span><span class="n">sk</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="nl">out</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">	<span class="k">return</span> <span class="n">err</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><p>如type注释所说this is really htons(ether_type)</p>
<p>packet_type 结构体第一个type 很重要 ，对应链路层中2个字节的以太网类型。而dev.c 链路层抓取的包上报给对应模块，就是根据抓取的链路层类型，然后给对应的模块处理，例如socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL)); ETH_P_ALL表示所有的底层包都会给到PF_PACKET 模块的处理函数，这里处理函数就是 packet_type.func 也就是在packet_create中设置的packet_rcv函数.</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span><span class="lnt">9
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="line"><span class="cl"><span class="k">static</span> <span class="kr">inline</span> <span class="kt">int</span> <span class="nf">deliver_skb</span><span class="p">(</span><span class="k">struct</span> <span class="n">sk_buff</span> <span class="o">*</span><span class="n">skb</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">			      <span class="k">struct</span> <span class="n">packet_type</span> <span class="o">*</span><span class="n">pt_prev</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">			      <span class="k">struct</span> <span class="n">net_device</span> <span class="o">*</span><span class="n">orig_dev</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">unlikely</span><span class="p">(</span><span class="n">skb_orphan_frags_rx</span><span class="p">(</span><span class="n">skb</span><span class="p">,</span> <span class="n">GFP_ATOMIC</span><span class="p">)))</span>
</span></span><span class="line"><span class="cl">		<span class="k">return</span> <span class="o">-</span><span class="n">ENOMEM</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">refcount_inc</span><span class="p">(</span><span class="o">&amp;</span><span class="n">skb</span><span class="o">-&gt;</span><span class="n">users</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="k">return</span> <span class="n">pt_prev</span><span class="o">-&gt;</span><span class="n">func</span><span class="p">(</span><span class="n">skb</span><span class="p">,</span> <span class="n">skb</span><span class="o">-&gt;</span><span class="n">dev</span><span class="p">,</span> <span class="n">pt_prev</span><span class="p">,</span> <span class="n">orig_dev</span><span class="p">);</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><h3 id="netpacketaf_packetcpacket_rcv">net/packet/af_packet.c/packet_rcv</h3>
<p>而对于packet_rcv() <br />
注释是This function makes lazy skb cloning in hope that most of packets are discarded by BPF.<br />
懒拷贝 希望大部分包能被BPF丢弃</p>
<p>注释还提到因为packets是由dev_queue_xmit_nit克隆而来</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt">  1
</span><span class="lnt">  2
</span><span class="lnt">  3
</span><span class="lnt">  4
</span><span class="lnt">  5
</span><span class="lnt">  6
</span><span class="lnt">  7
</span><span class="lnt">  8
</span><span class="lnt">  9
</span><span class="lnt"> 10
</span><span class="lnt"> 11
</span><span class="lnt"> 12
</span><span class="lnt"> 13
</span><span class="lnt"> 14
</span><span class="lnt"> 15
</span><span class="lnt"> 16
</span><span class="lnt"> 17
</span><span class="lnt"> 18
</span><span class="lnt"> 19
</span><span class="lnt"> 20
</span><span class="lnt"> 21
</span><span class="lnt"> 22
</span><span class="lnt"> 23
</span><span class="lnt"> 24
</span><span class="lnt"> 25
</span><span class="lnt"> 26
</span><span class="lnt"> 27
</span><span class="lnt"> 28
</span><span class="lnt"> 29
</span><span class="lnt"> 30
</span><span class="lnt"> 31
</span><span class="lnt"> 32
</span><span class="lnt"> 33
</span><span class="lnt"> 34
</span><span class="lnt"> 35
</span><span class="lnt"> 36
</span><span class="lnt"> 37
</span><span class="lnt"> 38
</span><span class="lnt"> 39
</span><span class="lnt"> 40
</span><span class="lnt"> 41
</span><span class="lnt"> 42
</span><span class="lnt"> 43
</span><span class="lnt"> 44
</span><span class="lnt"> 45
</span><span class="lnt"> 46
</span><span class="lnt"> 47
</span><span class="lnt"> 48
</span><span class="lnt"> 49
</span><span class="lnt"> 50
</span><span class="lnt"> 51
</span><span class="lnt"> 52
</span><span class="lnt"> 53
</span><span class="lnt"> 54
</span><span class="lnt"> 55
</span><span class="lnt"> 56
</span><span class="lnt"> 57
</span><span class="lnt"> 58
</span><span class="lnt"> 59
</span><span class="lnt"> 60
</span><span class="lnt"> 61
</span><span class="lnt"> 62
</span><span class="lnt"> 63
</span><span class="lnt"> 64
</span><span class="lnt"> 65
</span><span class="lnt"> 66
</span><span class="lnt"> 67
</span><span class="lnt"> 68
</span><span class="lnt"> 69
</span><span class="lnt"> 70
</span><span class="lnt"> 71
</span><span class="lnt"> 72
</span><span class="lnt"> 73
</span><span class="lnt"> 74
</span><span class="lnt"> 75
</span><span class="lnt"> 76
</span><span class="lnt"> 77
</span><span class="lnt"> 78
</span><span class="lnt"> 79
</span><span class="lnt"> 80
</span><span class="lnt"> 81
</span><span class="lnt"> 82
</span><span class="lnt"> 83
</span><span class="lnt"> 84
</span><span class="lnt"> 85
</span><span class="lnt"> 86
</span><span class="lnt"> 87
</span><span class="lnt"> 88
</span><span class="lnt"> 89
</span><span class="lnt"> 90
</span><span class="lnt"> 91
</span><span class="lnt"> 92
</span><span class="lnt"> 93
</span><span class="lnt"> 94
</span><span class="lnt"> 95
</span><span class="lnt"> 96
</span><span class="lnt"> 97
</span><span class="lnt"> 98
</span><span class="lnt"> 99
</span><span class="lnt">100
</span><span class="lnt">101
</span><span class="lnt">102
</span><span class="lnt">103
</span><span class="lnt">104
</span><span class="lnt">105
</span><span class="lnt">106
</span><span class="lnt">107
</span><span class="lnt">108
</span><span class="lnt">109
</span><span class="lnt">110
</span><span class="lnt">111
</span><span class="lnt">112
</span><span class="lnt">113
</span><span class="lnt">114
</span><span class="lnt">115
</span><span class="lnt">116
</span><span class="lnt">117
</span><span class="lnt">118
</span><span class="lnt">119
</span><span class="lnt">120
</span><span class="lnt">121
</span><span class="lnt">122
</span><span class="lnt">123
</span><span class="lnt">124
</span><span class="lnt">125
</span><span class="lnt">126
</span><span class="lnt">127
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="line"><span class="cl"><span class="cm">/*
</span></span></span><span class="line"><span class="cl"><span class="cm"> * This function makes lazy skb cloning in hope that most of packets
</span></span></span><span class="line"><span class="cl"><span class="cm"> * are discarded by BPF.
</span></span></span><span class="line"><span class="cl"><span class="cm"> *
</span></span></span><span class="line"><span class="cl"><span class="cm"> * Note tricky part: we DO mangle shared skb! skb-&gt;data, skb-&gt;len
</span></span></span><span class="line"><span class="cl"><span class="cm"> * and skb-&gt;cb are mangled. It works because (and until) packets
</span></span></span><span class="line"><span class="cl"><span class="cm"> * falling here are owned by current CPU. Output packets are cloned
</span></span></span><span class="line"><span class="cl"><span class="cm"> * by dev_queue_xmit_nit(), input packets are processed by net_bh
</span></span></span><span class="line"><span class="cl"><span class="cm"> * sequentially, so that if we return skb to original state on exit,
</span></span></span><span class="line"><span class="cl"><span class="cm"> * we will not harm anyone.
</span></span></span><span class="line"><span class="cl"><span class="cm"> */</span>
</span></span><span class="line"><span class="cl"><span class="k">static</span> <span class="kt">int</span> <span class="nf">packet_rcv</span><span class="p">(</span><span class="k">struct</span> <span class="n">sk_buff</span> <span class="o">*</span><span class="n">skb</span><span class="p">,</span> <span class="k">struct</span> <span class="n">net_device</span> <span class="o">*</span><span class="n">dev</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">		      <span class="k">struct</span> <span class="n">packet_type</span> <span class="o">*</span><span class="n">pt</span><span class="p">,</span> <span class="k">struct</span> <span class="n">net_device</span> <span class="o">*</span><span class="n">orig_dev</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl">	<span class="k">struct</span> <span class="n">sock</span> <span class="o">*</span><span class="n">sk</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">struct</span> <span class="n">sockaddr_ll</span> <span class="o">*</span><span class="n">sll</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">struct</span> <span class="n">packet_sock</span> <span class="o">*</span><span class="n">po</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">u8</span> <span class="o">*</span><span class="n">skb_head</span> <span class="o">=</span> <span class="n">skb</span><span class="o">-&gt;</span><span class="n">data</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">int</span> <span class="n">skb_len</span> <span class="o">=</span> <span class="n">skb</span><span class="o">-&gt;</span><span class="n">len</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">unsigned</span> <span class="kt">int</span> <span class="n">snaplen</span><span class="p">,</span> <span class="n">res</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="kt">bool</span> <span class="n">is_drop_n_account</span> <span class="o">=</span> <span class="nb">false</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">skb</span><span class="o">-&gt;</span><span class="n">pkt_type</span> <span class="o">==</span> <span class="n">PACKET_LOOPBACK</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">		<span class="k">goto</span> <span class="n">drop</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">sk</span> <span class="o">=</span> <span class="n">pt</span><span class="o">-&gt;</span><span class="n">af_packet_priv</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">po</span> <span class="o">=</span> <span class="n">pkt_sk</span><span class="p">(</span><span class="n">sk</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">net_eq</span><span class="p">(</span><span class="n">dev_net</span><span class="p">(</span><span class="n">dev</span><span class="p">),</span> <span class="n">sock_net</span><span class="p">(</span><span class="n">sk</span><span class="p">)))</span>
</span></span><span class="line"><span class="cl">		<span class="k">goto</span> <span class="n">drop</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">skb</span><span class="o">-&gt;</span><span class="n">dev</span> <span class="o">=</span> <span class="n">dev</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">dev_has_header</span><span class="p">(</span><span class="n">dev</span><span class="p">))</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">		<span class="cm">/* The device has an explicit notion of ll header,
</span></span></span><span class="line"><span class="cl"><span class="cm">		 * exported to higher levels.
</span></span></span><span class="line"><span class="cl"><span class="cm">		 *
</span></span></span><span class="line"><span class="cl"><span class="cm">		 * Otherwise, the device hides details of its frame
</span></span></span><span class="line"><span class="cl"><span class="cm">		 * structure, so that corresponding packet head is
</span></span></span><span class="line"><span class="cl"><span class="cm">		 * never delivered to user.
</span></span></span><span class="line"><span class="cl"><span class="cm">		 */</span>
</span></span><span class="line"><span class="cl">		<span class="k">if</span> <span class="p">(</span><span class="n">sk</span><span class="o">-&gt;</span><span class="n">sk_type</span> <span class="o">!=</span> <span class="n">SOCK_DGRAM</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">			<span class="n">skb_push</span><span class="p">(</span><span class="n">skb</span><span class="p">,</span> <span class="n">skb</span><span class="o">-&gt;</span><span class="n">data</span> <span class="o">-</span> <span class="n">skb_mac_header</span><span class="p">(</span><span class="n">skb</span><span class="p">));</span>
</span></span><span class="line"><span class="cl">		<span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="n">skb</span><span class="o">-&gt;</span><span class="n">pkt_type</span> <span class="o">==</span> <span class="n">PACKET_OUTGOING</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">			<span class="cm">/* Special case: outgoing packets have ll header at head */</span>
</span></span><span class="line"><span class="cl">			<span class="n">skb_pull</span><span class="p">(</span><span class="n">skb</span><span class="p">,</span> <span class="n">skb_network_offset</span><span class="p">(</span><span class="n">skb</span><span class="p">));</span>
</span></span><span class="line"><span class="cl">		<span class="p">}</span>
</span></span><span class="line"><span class="cl">	<span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">snaplen</span> <span class="o">=</span> <span class="n">skb</span><span class="o">-&gt;</span><span class="n">len</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="c1">// 根据设置的过滤规则过滤
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="n">res</span> <span class="o">=</span> <span class="n">run_filter</span><span class="p">(</span><span class="n">skb</span><span class="p">,</span> <span class="n">sk</span><span class="p">,</span> <span class="n">snaplen</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">res</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">		<span class="k">goto</span> <span class="n">drop_n_restore</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">snaplen</span> <span class="o">&gt;</span> <span class="n">res</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">		<span class="n">snaplen</span> <span class="o">=</span> <span class="n">res</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">atomic_read</span><span class="p">(</span><span class="o">&amp;</span><span class="n">sk</span><span class="o">-&gt;</span><span class="n">sk_rmem_alloc</span><span class="p">)</span> <span class="o">&gt;=</span> <span class="n">sk</span><span class="o">-&gt;</span><span class="n">sk_rcvbuf</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">		<span class="k">goto</span> <span class="n">drop_n_acct</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">skb_shared</span><span class="p">(</span><span class="n">skb</span><span class="p">))</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">		<span class="k">struct</span> <span class="n">sk_buff</span> <span class="o">*</span><span class="n">nskb</span> <span class="o">=</span> <span class="n">skb_clone</span><span class="p">(</span><span class="n">skb</span><span class="p">,</span> <span class="n">GFP_ATOMIC</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">		<span class="k">if</span> <span class="p">(</span><span class="n">nskb</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">			<span class="k">goto</span> <span class="n">drop_n_acct</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">		<span class="k">if</span> <span class="p">(</span><span class="n">skb_head</span> <span class="o">!=</span> <span class="n">skb</span><span class="o">-&gt;</span><span class="n">data</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">			<span class="n">skb</span><span class="o">-&gt;</span><span class="n">data</span> <span class="o">=</span> <span class="n">skb_head</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">			<span class="n">skb</span><span class="o">-&gt;</span><span class="n">len</span> <span class="o">=</span> <span class="n">skb_len</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">		<span class="p">}</span>
</span></span><span class="line"><span class="cl">		<span class="n">consume_skb</span><span class="p">(</span><span class="n">skb</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">		<span class="n">skb</span> <span class="o">=</span> <span class="n">nskb</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">sock_skb_cb_check_size</span><span class="p">(</span><span class="k">sizeof</span><span class="p">(</span><span class="o">*</span><span class="n">PACKET_SKB_CB</span><span class="p">(</span><span class="n">skb</span><span class="p">))</span> <span class="o">+</span> <span class="n">MAX_ADDR_LEN</span> <span class="o">-</span> <span class="mi">8</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">sll</span> <span class="o">=</span> <span class="o">&amp;</span><span class="n">PACKET_SKB_CB</span><span class="p">(</span><span class="n">skb</span><span class="p">)</span><span class="o">-&gt;</span><span class="n">sa</span><span class="p">.</span><span class="n">ll</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">sll</span><span class="o">-&gt;</span><span class="n">sll_hatype</span> <span class="o">=</span> <span class="n">dev</span><span class="o">-&gt;</span><span class="n">type</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">sll</span><span class="o">-&gt;</span><span class="n">sll_pkttype</span> <span class="o">=</span> <span class="n">skb</span><span class="o">-&gt;</span><span class="n">pkt_type</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">unlikely</span><span class="p">(</span><span class="n">po</span><span class="o">-&gt;</span><span class="n">origdev</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">		<span class="n">sll</span><span class="o">-&gt;</span><span class="n">sll_ifindex</span> <span class="o">=</span> <span class="n">orig_dev</span><span class="o">-&gt;</span><span class="n">ifindex</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="k">else</span>
</span></span><span class="line"><span class="cl">		<span class="n">sll</span><span class="o">-&gt;</span><span class="n">sll_ifindex</span> <span class="o">=</span> <span class="n">dev</span><span class="o">-&gt;</span><span class="n">ifindex</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">sll</span><span class="o">-&gt;</span><span class="n">sll_halen</span> <span class="o">=</span> <span class="n">dev_parse_header</span><span class="p">(</span><span class="n">skb</span><span class="p">,</span> <span class="n">sll</span><span class="o">-&gt;</span><span class="n">sll_addr</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="cm">/* sll-&gt;sll_family and sll-&gt;sll_protocol are set in packet_recvmsg().
</span></span></span><span class="line"><span class="cl"><span class="cm">	 * Use their space for storing the original skb length.
</span></span></span><span class="line"><span class="cl"><span class="cm">	 */</span>
</span></span><span class="line"><span class="cl">	<span class="n">PACKET_SKB_CB</span><span class="p">(</span><span class="n">skb</span><span class="p">)</span><span class="o">-&gt;</span><span class="n">sa</span><span class="p">.</span><span class="n">origlen</span> <span class="o">=</span> <span class="n">skb</span><span class="o">-&gt;</span><span class="n">len</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">pskb_trim</span><span class="p">(</span><span class="n">skb</span><span class="p">,</span> <span class="n">snaplen</span><span class="p">))</span>
</span></span><span class="line"><span class="cl">		<span class="k">goto</span> <span class="n">drop_n_acct</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="n">skb_set_owner_r</span><span class="p">(</span><span class="n">skb</span><span class="p">,</span> <span class="n">sk</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="n">skb</span><span class="o">-&gt;</span><span class="n">dev</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">skb_dst_drop</span><span class="p">(</span><span class="n">skb</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="cm">/* drop conntrack reference */</span>
</span></span><span class="line"><span class="cl">	<span class="n">nf_reset_ct</span><span class="p">(</span><span class="n">skb</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">	<span class="c1">// 最后将底层网口符合应用层的数据复制到接收缓存队列中 这样应用层就得到了网络流量
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>	<span class="n">spin_lock</span><span class="p">(</span><span class="o">&amp;</span><span class="n">sk</span><span class="o">-&gt;</span><span class="n">sk_receive_queue</span><span class="p">.</span><span class="n">lock</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="n">po</span><span class="o">-&gt;</span><span class="n">stats</span><span class="p">.</span><span class="n">stats1</span><span class="p">.</span><span class="n">tp_packets</span><span class="o">++</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">sock_skb_set_dropcount</span><span class="p">(</span><span class="n">sk</span><span class="p">,</span> <span class="n">skb</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="n">__skb_queue_tail</span><span class="p">(</span><span class="o">&amp;</span><span class="n">sk</span><span class="o">-&gt;</span><span class="n">sk_receive_queue</span><span class="p">,</span> <span class="n">skb</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="n">spin_unlock</span><span class="p">(</span><span class="o">&amp;</span><span class="n">sk</span><span class="o">-&gt;</span><span class="n">sk_receive_queue</span><span class="p">.</span><span class="n">lock</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="n">sk</span><span class="o">-&gt;</span><span class="n">sk_data_ready</span><span class="p">(</span><span class="n">sk</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nl">drop_n_acct</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">	<span class="n">is_drop_n_account</span> <span class="o">=</span> <span class="nb">true</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="n">atomic_inc</span><span class="p">(</span><span class="o">&amp;</span><span class="n">po</span><span class="o">-&gt;</span><span class="n">tp_drops</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="n">atomic_inc</span><span class="p">(</span><span class="o">&amp;</span><span class="n">sk</span><span class="o">-&gt;</span><span class="n">sk_drops</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nl">drop_n_restore</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="n">skb_head</span> <span class="o">!=</span> <span class="n">skb</span><span class="o">-&gt;</span><span class="n">data</span> <span class="o">&amp;&amp;</span> <span class="n">skb_shared</span><span class="p">(</span><span class="n">skb</span><span class="p">))</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">		<span class="n">skb</span><span class="o">-&gt;</span><span class="n">data</span> <span class="o">=</span> <span class="n">skb_head</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">		<span class="n">skb</span><span class="o">-&gt;</span><span class="n">len</span> <span class="o">=</span> <span class="n">skb_len</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">	<span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="nl">drop</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">	<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">is_drop_n_account</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">		<span class="n">consume_skb</span><span class="p">(</span><span class="n">skb</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="k">else</span>
</span></span><span class="line"><span class="cl">		<span class="n">kfree_skb</span><span class="p">(</span><span class="n">skb</span><span class="p">);</span>
</span></span><span class="line"><span class="cl">	<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><h3 id="netpacketaf_packetcpacket_recvmsg">net/packet/af_packet.c/packet_recvmsg</h3>
<p>应用层创建socket，底层会关联上这个socket，一旦关联上链路层抓到的包就会copy一份给上层接口（即PF_PACKET 注册的回调函数packet_rev）. 而回调函数会根据应用层设置的bpf过滤数据包，最终放入接收缓存的数据包肯定是符合应用层想截取的数据。因此最后一步recvfrom也就是从接收缓存的数据包copy给应用层</p>
<p>recvfrom的系统调用链如下</p>
<p>__sys_recvfrom-&gt;sock_recvmsg-&gt;sk.ops.recvmsg</p>
<p>此处的recvmsg就是af_packet.c中绑定的packet_recvmsg</p>
<p>而packet_recvmsg的官方注释是 Pull a packet from our receive queue and hand it to the user.<br />
从接收队列拉取packet传递给用户</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre tabindex="0" class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span><span class="lnt">14
</span><span class="lnt">15
</span></code></pre></td>
<td class="lntd">
<pre tabindex="0" class="chroma"><code class="language-c" data-lang="c"><span class="line"><span class="cl"><span class="k">static</span> <span class="k">const</span> <span class="k">struct</span> <span class="n">proto_ops</span> <span class="n">packet_ops</span> <span class="o">=</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl"><span class="p">...</span>
</span></span><span class="line"><span class="cl">	<span class="p">.</span><span class="n">recvmsg</span> <span class="o">=</span>	<span class="n">packet_recvmsg</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">	<span class="p">.</span><span class="n">mmap</span> <span class="o">=</span>		<span class="n">packet_mmap</span><span class="p">,</span>
</span></span><span class="line"><span class="cl"><span class="p">...</span>
</span></span><span class="line"><span class="cl"><span class="p">};</span>
</span></span><span class="line"><span class="cl"><span class="cm">/*
</span></span></span><span class="line"><span class="cl"><span class="cm"> *	Pull a packet from our receive queue and hand it to the user.
</span></span></span><span class="line"><span class="cl"><span class="cm"> *	If necessary we block.
</span></span></span><span class="line"><span class="cl"><span class="cm"> */</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">static</span> <span class="kt">int</span> <span class="nf">packet_recvmsg</span><span class="p">(</span><span class="k">struct</span> <span class="n">socket</span> <span class="o">*</span><span class="n">sock</span><span class="p">,</span> <span class="k">struct</span> <span class="n">msghdr</span> <span class="o">*</span><span class="n">msg</span><span class="p">,</span> <span class="n">size_t</span> <span class="n">len</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">			  <span class="kt">int</span> <span class="n">flags</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">{</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></td></tr></table>
</div>
</div><h3 id="recvfrom-cap">recvfrom cap</h3>
<p>到这里用户创建socket然后使用recvfrom系统调用抓取网络流量的过程结束</p>
<p>可以看到这个网络抓包流程经历了多次内存拷贝的过程(从链路层copy给上层接口 再从接收队列copy到用户空间)</p>
<h2 id="to-do">To do</h2>
<ul>
<li>pcap_activate_linux()中混杂模式和&quot;any&quot; device</li>
<li>2020n1ctf W2L kernelpwn</li>
</ul>
<h2 id="changelog">ChangeLog</h2>
<p>socket(PF_PACKET, SOCK_RAW/SOCK_DGRAM, htons(ETH_P_ALL))/socket(PF_INET, SOCK_PACKET, htons(ETH_P_ALL))</p>
<p>0.9 live_open_new/live_open_old pcap_read_packet&amp;recvfrom<br />
1.0 activate_new-&gt;activate_mmap/active_old pcap_read_linux_mmap/pcap_read_packet&amp;recvfrom<br />
1.9 activate_pf_packet/activate_sock_packet pcap_read_packet/pcap_read_linux_mmap_v1[_64]/2/3	recvfrom<br />
1.10 activate_pf_packet		pcap_read_linux_mmap_v2/3</p>
<p>1.9添加DLT_LINUX_SLL2的support,1.10新增DLT_LINUX_SLL2对cooked-mode captures的支持</p>
<p>1.10<br />
Require PF_PACKET support, and kernel 2.6.27 or later<br />
Handle systems without AF_INET or AF_UNIX socket support</p>
<p>可以看到版本更迭差别还是挺大的</p>
<h2 id="reference">Reference</h2>
<p><a href="https://mp.weixin.qq.com/s/ZX8Jluh-RgJXcVh3OvycRQ%5Bhow">https://mp.weixin.qq.com/s/ZX8Jluh-RgJXcVh3OvycRQ[how</a> tcpdump cap]<br />
<a href="https://blog.csdn.net/bie_niu1992/article/details/96435670%5Btcpdump-libpcap%5D">https://blog.csdn.net/bie_niu1992/article/details/96435670[tcpdump-libpcap]</a><br />
<a href="https://zh.wikipedia.org/zh-hans/BPF%5BBPF%5D">https://zh.wikipedia.org/zh-hans/BPF[BPF]</a><br />
<a href="https://www.tcpdump.org/manpages/tcpdump.1.html%5Btcpdump">https://www.tcpdump.org/manpages/tcpdump.1.html[tcpdump</a> man]<br />
<a href="https://www.compuquip.com/blog/tuning-ring-buffer-checkpoint-firewall%5Bring">https://www.compuquip.com/blog/tuning-ring-buffer-checkpoint-firewall[ring</a> buffer]<br />
<a href="https://www.cnblogs.com/10087622blog/p/8320234.html%5Blibpcap">https://www.cnblogs.com/10087622blog/p/8320234.html[libpcap</a> mmap]<br />
<a href="https://stackoverflow.com/questions/60736230/why-libpcap-is-better-than-sniffing-with-raw%5Blibpcap">https://stackoverflow.com/questions/60736230/why-libpcap-is-better-than-sniffing-with-raw[libpcap</a> better than raw socket]<br />
<a href="https://blog.csdn.net/gengzhikui1992/article/details/103142848%5Bcap">https://blog.csdn.net/gengzhikui1992/article/details/103142848[cap</a> speed compare]<br />
<a href="http://blog.chinaunix.net/uid-23069658-id-3141409.html">http://blog.chinaunix.net/uid-23069658-id-3141409.html</a> <br />
<a href="http://blog.chinaunix.net/uid-20357359-id-1963684.html">http://blog.chinaunix.net/uid-20357359-id-1963684.html</a><br />
<a href="https://zhuanlan.zhihu.com/p/345901595">https://zhuanlan.zhihu.com/p/345901595</a></p>

    </article>
    
    
<script defer src="/js/clipboard.min.c168d3a04c45a631be76437054619a4a3b30107960cb9730be96012fef5762b0.js"></script>

<script defer src="/js/helper/prev.min.js"></script>

<script defer src="/js/helper/prop.min.js"></script>
<script>
  'use strict';
  document.addEventListener('DOMContentLoaded', function () {
    
    var clipInit = false;
    var preChromaElem = document.querySelectorAll('pre.chroma');
    var langCodeElem = document.querySelectorAll('.language-code');
    var dollarCodeElem = document.querySelectorAll('div.language-\\$');
    var gtCodeElem = document.querySelectorAll('div.language-\\>');

    var makeClipboard = function(elem) {
      var code = elem,
          text = elem.textContent;
        
      if (text.length > 15) {
        if (!clipInit) {
          var text, clip = new ClipboardJS('.copy-to-clipboard', {
            text: function (trigger) {
              var codeElem = prev(trigger).querySelectorAll('code');
              if (codeElem.length > 1) {
                text = prev(trigger).querySelector('code[class^="language-"]').textContent;
              } else {
                text = prev(trigger).querySelector('code').textContent;
              }

              return text.replace(/^\$\s/gm, '');
            }
          });

          var inPre;
          clip.on('success', function (e) {
            e.clearSelection();
            inPre = prop(e.trigger.parentNode, 'tagName') == 'PRE';
            e.trigger.setAttribute('aria-label', 'Copied to clipboard!');
            e.trigger.classList.add('tooltipped');
            e.trigger.classList.add('tooltipped-w');
          });

          clip.on('error', function (e) {
            inPre = prop(e.trigger.parentNode, 'tagName') == 'PRE';
            e.trigger.setAttribute('aria-label', e.action.toString());
            e.trigger.classList.add('tooltipped');
            e.trigger.classList.add('tooltipped-w');
          });

          clipInit = true;
        }

        var notAllowedClass = ['language-mermaid', 'language-viz', 'language-wave', 'language-chart', 'language-msc', 'language-flowchart'];
        var isNotAllowedIncluded = false;
        var curClassName = code.getAttribute('class');

        for (var i = 0; i < notAllowedClass.length; i++) {
          if (curClassName && curClassName.startsWith(notAllowedClass[i])) {
            isNotAllowedIncluded = true;
            break;
          }
        }

        if (!isNotAllowedIncluded) {
          if (curClassName) {
            var newClipboardElem = document.createElement('span');
            newClipboardElem.setAttribute('class', 'copy-to-clipboard');
            newClipboardElem.setAttribute('title', 'Copy to clipboard');
            elem.parentNode.parentNode.insertBefore(newClipboardElem, elem.parentNode.nextElementSibling);
          }
        }
      }
    }

    var makeSymbolClipboard = function(elem) {
      var clipboardSpan = document.createElement('span');
      clipboardSpan.setAttribute('class', 'copy-to-clipboard');
      clipboardSpan.setAttribute('title', 'Copy to clipboard');
      elem.parentNode.parentNode.insertBefore(clipboardSpan, elem.parentNode.nextElementSibling);
    }

    preChromaElem ? 
    preChromaElem.forEach(function(elem) {
      elem.querySelectorAll('code').forEach(function(codeElem) {
        makeClipboard(codeElem);
      });
    }) : null;
    
    langCodeElem ? 
    langCodeElem.forEach(function(elem) {
      elem.querySelectorAll('code').forEach(function (codeElem) {
        makeClipboard(codeElem);
      });
    }) : null;

    dollarCodeElem ? 
    dollarCodeElem.forEach(function(elem) {
      elem.querySelectorAll('code').forEach(function (codeElem) {
        makeSymbolClipboard(codeElem);
      });
    }) : null;

    gtCodeElem ?
    gtCodeElem.forEach(function(elem) {
      elem.querySelectorAll('code').forEach(function (codeElem) {
        makeSymbolClipboard(codeElem);
      });
    }) : null;
    
  });
</script>
    <script>
  'use strict';
  
  function wrap(el, wrapper) {
    el.parentNode.insertBefore(wrapper, el);
    wrapper.appendChild(el);
  }

  (function () {
    var singleContentsElem = document.querySelector('.single__contents');
    singleContentsElem ? 
    singleContentsElem.querySelectorAll('pre > code').forEach(function(elem) {
      var dataLang = elem.getAttribute('data-lang');
      var dataLangWrapper = document.createElement('div');
      var code = null;
      var codeTitle = null;

      if (dataLang && dataLang.includes(':')) {
        code = dataLang.split(':')[0];
        codeTitle = dataLang.split(':')[1];

        dataLangWrapper.className = 'language-' + code;
        dataLangWrapper.setAttribute('data-lang', codeTitle);

        elem.className = 'language-' + code;
        elem.setAttribute('data-lang', codeTitle);
        elem.setAttribute('id', codeTitle);
      } else if (!dataLang) {
        dataLangWrapper.setAttribute('data-lang', 'Code');
        dataLangWrapper.className = 'language-code';
      }

      if (!dataLang || codeTitle) {
        wrap(elem.parentNode, dataLangWrapper);
      }

    }) : null;
  })();

  var langCodeElem = document.querySelectorAll('.language-code');
  langCodeElem ? langCodeElem.forEach(function (elem) {
    var newElem = document.createElement('span');
    newElem.className = 'copy-to-clipboard';
    newElem.setAttribute('title', 'Copy to clipboard');
    elem.append(newElem);
  }) : null;
  

  

  
  var dollarCodeElem = document.querySelectorAll('div.language-\\$');
  var gtCodeElem = document.querySelectorAll('div.language-\\>');

  dollarCodeElem ?
  dollarCodeElem.forEach(function(elem) {
    var lnts = elem.parentNode.parentNode ? elem.parentNode.parentNode.querySelectorAll('.lnt') : null;
    lnts ? 
    lnts.forEach(function(lnt) {
      lnt.innerHTML = '$<br/>';
    }) : null;
  }) : null;

  gtCodeElem ?
  gtCodeElem.forEach(function(elem) {
    var lnts = elem.parentNode.parentNode ? elem.parentNode.parentNode.querySelectorAll('.lnt') : null;
    lnts ? 
    lnts.forEach(function(lnt) {
      lnt.innerHTML = '><br/>';
    }) : null;
  }) : null;
  
</script>
    
<div class="donation">
  <div class="donation__message">
    Share on
  </div>
  <div class="donation__icons">
    
    
    
      
    
      
    
  </div>
</div>


    
    
<div class="whoami__gutter"></div>
<hr class="hr-slash whoami-hr"/>
<section class="whoami">
  <div class="whoami__image-wrapper">
    
    
      
        <img data-src="/images/whoami/avatar.jpg" src="data:image/svg+xml,%0A%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath fill='none' d='M0 0h24v24H0V0z'/%3E%3Cpath fill='%23aaa' d='M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-1 16H6c-.55 0-1-.45-1-1V6c0-.55.45-1 1-1h12c.55 0 1 .45 1 1v12c0 .55-.45 1-1 1zm-4.44-6.19l-2.35 3.02-1.56-1.88c-.2-.25-.58-.24-.78.01l-1.74 2.23c-.26.33-.02.81.39.81h8.98c.41 0 .65-.47.4-.8l-2.55-3.39c-.19-.26-.59-.26-.79 0z'/%3E%3C/svg%3E" alt="ruokeqx" class="lazyload whoami__image"/>
      
    
  </div>
  <div class="whoami__contents">
    <div class="whoami__written-by">
      WRITTEN BY
    </div>
    <div class="whoami__title">
      
        ruokeqx
      
    </div>
    <div class="whoami__desc">
      
        
      
    </div>
    <div class="whoami__social">
      
      
      
      
      
      
      
      
      <a href="ruokeqx@163.com" title="email" aria-label="email">
        <svg xmlns="http://www.w3.org/2000/svg" width="25" height="25" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0V0z"/><path fill="currentColor" d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-.4 4.25l-7.07 4.42c-.32.2-.74.2-1.06 0L4.4 8.25c-.25-.16-.4-.43-.4-.72 0-.67.73-1.07 1.3-.72L12 11l6.7-4.19c.57-.35 1.3.05 1.3.72 0 .29-.15.56-.4.72z"/></svg>
      </a>
      
      
      
      
      
      
      
      <a href="https://github.com/ruokeqx" title="github" aria-label="github">
        <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="25" height="25" viewBox="0 0 24 24" version="1.1">
<g id="surface3680">
<path fill="currentColor" d="M 10.898438 2.101562 C 6.300781 2.601562 2.601562 6.300781 2.101562 10.800781 C 1.601562 15.5 4.300781 19.699219 8.398438 21.300781 C 8.699219 21.398438 9 21.199219 9 20.800781 L 9 19.199219 C 9 19.199219 8.601562 19.300781 8.101562 19.300781 C 6.699219 19.300781 6.101562 18.101562 6 17.398438 C 5.898438 17 5.699219 16.699219 5.398438 16.398438 C 5.101562 16.300781 5 16.300781 5 16.199219 C 5 16 5.300781 16 5.398438 16 C 6 16 6.5 16.699219 6.699219 17 C 7.199219 17.800781 7.800781 18 8.101562 18 C 8.5 18 8.800781 17.898438 9 17.800781 C 9.101562 17.101562 9.398438 16.398438 10 16 C 7.699219 15.5 6 14.199219 6 12 C 6 10.898438 6.5 9.800781 7.199219 9 C 7.101562 8.800781 7 8.300781 7 7.601562 C 7 7.199219 7 6.601562 7.300781 6 C 7.300781 6 8.699219 6 10.101562 7.300781 C 10.601562 7.101562 11.300781 7 12 7 C 12.699219 7 13.398438 7.101562 14 7.300781 C 15.300781 6 16.800781 6 16.800781 6 C 17 6.601562 17 7.199219 17 7.601562 C 17 8.398438 16.898438 8.800781 16.800781 9 C 17.5 9.800781 18 10.800781 18 12 C 18 14.199219 16.300781 15.5 14 16 C 14.601562 16.5 15 17.398438 15 18.300781 L 15 20.898438 C 15 21.199219 15.300781 21.5 15.699219 21.398438 C 19.398438 19.898438 22 16.300781 22 12.101562 C 22 6.101562 16.898438 1.398438 10.898438 2.101562 Z M 10.898438 2.101562 "/>
</g>
</svg>

      </a>
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    </div>
  </div>
</section>
<hr class="hr-slash whoami-hr" />


    <section class="related">
    
    
  </section>
    <div class="grow"></div>
<nav class="pagination-single">
  
    
      <a href="https://ruokeqx.gitee.io/posts/mit6.824-lab/" class="pagination-single__left">
        <div class="pagination-single__icon">
          <svg xmlns="http://www.w3.org/2000/svg" width="25" height="25" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0V0z"/><path fill="currentColor" d="M19 11H7.83l4.88-4.88c.39-.39.39-1.03 0-1.42-.39-.39-1.02-.39-1.41 0l-6.59 6.59c-.39.39-.39 1.02 0 1.41l6.59 6.59c.39.39 1.02.39 1.41 0 .39-.39.39-1.02 0-1.41L7.83 13H19c.55 0 1-.45 1-1s-.45-1-1-1z"/></svg>
        </div>
        <div class="pagination-single__left-title">MIT 6.824 lab</div>      
      </a>
    
    <div class="grow"></div>
    
      <a href="https://ruokeqx.gitee.io/posts/ethereum101/" class="pagination-single__right">      
        <div class="pagination-single__right-title">《Mastering Ethereum》笔记及EVM字节码逆向</div>
        <div class="pagination-single__icon">
          <svg xmlns="http://www.w3.org/2000/svg" width="25" height="25" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0V0z"/><path fill="currentColor" d="M5 13h11.17l-4.88 4.88c-.39.39-.39 1.03 0 1.42.39.39 1.02.39 1.41 0l6.59-6.59c.39-.39.39-1.02 0-1.41l-6.58-6.6c-.39-.39-1.02-.39-1.41 0-.39.39-.39 1.02 0 1.41L16.17 11H5c-.55 0-1 .45-1 1s.45 1 1 1z"/></svg>
        </div>
      </a>
    
  
</nav>
    
    <div class="modal micromodal-slide" id="modal" aria-hidden="true">
  <div class="modal__overlay" tabindex="-1" data-micromodal-close>
    <div class="modal__container" role="dialog" aria-modal="true" aria-labelledby="modal-title">
      
      <div class="modal__content" id="modal-content">
        <div id="mySwipe" class="swipe">
          <div class="swipe-wrap">
          </div>
        </div>
      </div>

      <span class="modal__items">
        
        <span class="modal__header">
          <div class="modal__paging" title="Page Info" aria-label="Current Page">
          </div>
          <div class="modal__icon modal__toolbar modal__toolbar--close" title="Close" aria-label="Close Button" data-micromodal-close>
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 26 26" width="25" height="25"><path fill="currentColor" d="M 21.734375 19.640625 L 19.636719 21.734375 C 19.253906 22.121094 18.628906 22.121094 18.242188 21.734375 L 13 16.496094 L 7.761719 21.734375 C 7.375 22.121094 6.746094 22.121094 6.363281 21.734375 L 4.265625 19.640625 C 3.878906 19.253906 3.878906 18.628906 4.265625 18.242188 L 9.503906 13 L 4.265625 7.761719 C 3.882813 7.371094 3.882813 6.742188 4.265625 6.363281 L 6.363281 4.265625 C 6.746094 3.878906 7.375 3.878906 7.761719 4.265625 L 13 9.507813 L 18.242188 4.265625 C 18.628906 3.878906 19.257813 3.878906 19.636719 4.265625 L 21.734375 6.359375 C 22.121094 6.746094 22.121094 7.375 21.738281 7.761719 L 16.496094 13 L 21.734375 18.242188 C 22.121094 18.628906 22.121094 19.253906 21.734375 19.640625 Z"/></svg>
          </div>
          <div class="modal__icon modal__toolbar modal__toolbar--full" title="Full Screen" aria-label="Full Screen Button">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="25" height="25"><path fill="currentColor" d="M 5 3 C 3.9069372 3 3 3.9069372 3 5 L 3 8 A 1.0001 1.0001 0 1 0 5 8 L 5 5 L 8 5 A 1.0001 1.0001 0 1 0 8 3 L 5 3 z M 16 3 A 1.0001 1.0001 0 1 0 16 5 L 19 5 L 19 8 A 1.0001 1.0001 0 1 0 21 8 L 21 5 C 21 3.9069372 20.093063 3 19 3 L 16 3 z M 3.984375 14.986328 A 1.0001 1.0001 0 0 0 3 16 L 3 19 C 3 20.093063 3.9069372 21 5 21 L 8 21 A 1.0001 1.0001 0 1 0 8 19 L 5 19 L 5 16 A 1.0001 1.0001 0 0 0 3.984375 14.986328 z M 19.984375 14.986328 A 1.0001 1.0001 0 0 0 19 16 L 19 19 L 16 19 A 1.0001 1.0001 0 1 0 16 21 L 19 21 C 20.093063 21 21 20.093063 21 19 L 21 16 A 1.0001 1.0001 0 0 0 19.984375 14.986328 z"/></svg>
          </div>
          <div class="modal__icon modal__toolbar modal__toolbar--normal" title="Normal Screen" aria-label="Normal Screen Button">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50" width="25" height="25"><path fill="currentColor" d="M 16.96875 4.972656 C 15.867188 4.988281 14.984375 5.894531 15 7 L 15 15 L 7 15 C 6.277344 14.988281 5.609375 15.367188 5.246094 15.992188 C 4.878906 16.613281 4.878906 17.386719 5.246094 18.007813 C 5.609375 18.632813 6.277344 19.011719 7 19 L 19 19 L 19 7 C 19.007813 6.460938 18.796875 5.941406 18.414063 5.558594 C 18.03125 5.175781 17.511719 4.964844 16.96875 4.972656 Z M 32.96875 4.972656 C 31.921875 4.988281 31.0625 5.8125 31.003906 6.859375 C 31 6.90625 31 6.953125 31 7 L 31 19 L 43 19 C 43.066406 19 43.132813 19 43.199219 18.992188 C 44.269531 18.894531 45.070313 17.972656 45.015625 16.902344 C 44.964844 15.828125 44.074219 14.988281 43 15 L 35 15 L 35 7 C 35.007813 6.460938 34.796875 5.941406 34.414063 5.558594 C 34.03125 5.175781 33.511719 4.964844 32.96875 4.972656 Z M 7 31 C 6.277344 30.988281 5.609375 31.367188 5.246094 31.992188 C 4.878906 32.613281 4.878906 33.386719 5.246094 34.007813 C 5.609375 34.632813 6.277344 35.011719 7 35 L 15 35 L 15 43 C 14.988281 43.722656 15.367188 44.390625 15.992188 44.753906 C 16.613281 45.121094 17.386719 45.121094 18.007813 44.753906 C 18.632813 44.390625 19.011719 43.722656 19 43 L 19 31 Z M 31 31 L 31 43 C 30.988281 43.722656 31.367188 44.390625 31.992188 44.753906 C 32.613281 45.121094 33.386719 45.121094 34.007813 44.753906 C 34.632813 44.390625 35.011719 43.722656 35 43 L 35 35 L 43 35 C 43.722656 35.011719 44.390625 34.632813 44.753906 34.007813 C 45.121094 33.386719 45.121094 32.613281 44.753906 31.992188 C 44.390625 31.367188 43.722656 30.988281 43 31 Z"/></svg>
          </div>
        </span>
        
        <div class="modal__icon modal__arrow modal__arrow--left" title="Arrow Left" aria-label="Arrow Left Button">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 26 26" width="28" height="28"><path fill="currentColor" d="M 23.28125 11 L 10 10 L 10 6.851563 C 10 6.523438 9.839844 6.277344 9.519531 6.03125 C 9.199219 5.949219 8.878906 5.949219 8.640625 6.113281 C 5.359375 8.410156 2.238281 12.257813 2.160156 12.421875 C 2.082031 12.578125 2.007813 12.8125 2.003906 12.976563 C 2.003906 12.980469 2 12.988281 2 12.992188 C 2 13.15625 2.078125 13.402344 2.160156 13.484375 C 2.238281 13.648438 5.28125 17.507813 8.640625 19.804688 C 8.960938 19.96875 9.28125 20.050781 9.519531 19.886719 C 9.839844 19.722656 10 19.476563 10 19.148438 L 10 16 L 23.28125 15 C 23.679688 14.679688 24 13.875 24 12.992188 C 24 12.195313 23.761719 11.320313 23.28125 11 Z"/></svg>
        </div>
        
        <div class="modal__icon modal__arrow modal__arrow--right" title="Arrow Right" aria-label="Arrow Right Button">

          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 26 26" width="28" height="28"><path fill="currentColor" d="M 2.71875 11.023438 L 16 10.023438 L 16 6.875 C 16 6.546875 16.160156 6.300781 16.480469 6.054688 C 16.800781 5.972656 17.121094 5.972656 17.359375 6.136719 C 20.640625 8.433594 23.761719 12.28125 23.839844 12.445313 C 23.917969 12.601563 23.992188 12.835938 23.996094 13 C 23.996094 13.003906 24 13.011719 24 13.015625 C 24 13.179688 23.921875 13.425781 23.839844 13.507813 C 23.761719 13.671875 20.71875 17.53125 17.359375 19.828125 C 17.039063 19.992188 16.71875 20.074219 16.480469 19.910156 C 16.160156 19.746094 16 19.5 16 19.171875 L 16 16.023438 L 2.71875 15.023438 C 2.320313 14.703125 2 13.898438 2 13.015625 C 2 12.21875 2.238281 11.34375 2.71875 11.023438 Z"/></svg>
        </div>

        <div class="modal__caption">
          <div class="modal__caption--text">
          </div>
        </div>

      </span>
    </div>
  </div>
</div>


<script defer src="/js/swipe.min.b5af2be70ffc9ba2e83412609aa18b5b025c69399f9e1dce09d444a636a38cd0.js"></script>

<script defer src="/js/micromodal.min.de01b44b2f383056bbcaf6ee921fd385d79108ec1129afd0eb2f3f5a07e11f45.js"></script>

<script defer src="/js/helper/fadeinout.min.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function () {
  
   
  var docElem = document.documentElement;

   
  function openFullscreen() {
    if (docElem.requestFullscreen) {
      docElem.requestFullscreen();
    } else if (docElem.mozRequestFullScreen) {  
      docElem.mozRequestFullScreen();
    } else if (docElem.webkitRequestFullscreen) {  
      docElem.webkitRequestFullscreen();
    } else if (docElem.msRequestFullscreen) {  
      docElem.msRequestFullscreen();
    }
  }

   
  function closeFullscreen() {
    if (document.fullscreenElement ||
      document.webkitFullscreenElement ||
      document.mozFullScreenElement) {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.mozCancelFullScreen) {  
        document.mozCancelFullScreen();
      } else if (document.webkitExitFullscreen) {  
        document.webkitExitFullscreen();
      } else if (document.msExitFullscreen) {  
        document.msExitFullscreen();
      }
    }
  }

  var modal = document.getElementById('modal');
  var galleryContainerElem = document.querySelector('.gallery__container');
  var swipeWrapElem = document.querySelector('.swipe-wrap');
  var mySwipeElem = document.getElementById('mySwipe');
  var arrowLeftElem = document.querySelector('.modal__arrow--left');
  var arrowRightElem = document.querySelector('.modal__arrow--right');
  var closeElem = document.querySelector('.modal__toolbar--close');
  var fullElem = document.querySelector('.modal__toolbar--full');
  var normalElem = document.querySelector('.modal__toolbar--normal');
  var captionElem = document.querySelector('.modal__caption');
  var pagingElem = document.querySelector('.modal__paging');
  var itemsElem = document.querySelector('.modal__items');
  var imgTotalNum = null;
  var myFadeTimeout = null;
  var mySwipe = null;
  var keydownFunction = function (e) {
    if (e.key === 'ArrowRight') {
      if (modal && modal.classList.contains('is-open')) {
        mySwipe.next();
      }
    } else if (e.key === 'ArrowLeft') {
      if (modal && modal.classList.contains('is-open')) {
        mySwipe.prev();
      }
    }
  }

  if (galleryContainerElem) {
    imgTotalNum = galleryContainerElem.querySelectorAll('img').length;
  } else {
    galleryContainerElem = document.querySelector('.single__contents');
    imgTotalNum = galleryContainerElem.querySelectorAll('img').length;
  }

  MicroModal.init({
    onClose: function () {
      if (mySwipe) {
        mySwipe.kill();
        mySwipe = null;
        closeFullscreen();
      }
      window.removeEventListener('keydown', keydownFunction);
    },
    disableScroll: true,
    disableFocus: true,
    awaitOpenAnimation: false,
    awaitCloseAnimation: false,
    debugMode: false,
  });

  var imageLoad = function(src) {
    return new Promise(function(resolve, reject) {
      var newImg = new Image;
      newImg.onload = function() {
        resolve(newImg);
      }
      newImg.onerror = reject;
      newImg.src = src;
    });
  }

  galleryContainerElem.querySelectorAll('img').forEach(function (elem, idx) {
    elem.style.cursor = 'pointer';

    var clonedElem = elem.cloneNode(true);
    clonedElem.style.maxHeight = '100%';
    clonedElem.style.maxWidth = '100%';
    clonedElem.onclick = function (e) {
      e.stopPropagation();
    }

    var wrapper = document.createElement('div');
    wrapper.style.width = '100%';
    wrapper.style.height = '100vh';
    wrapper.setAttribute('data-micromodal-close', '');
    wrapper.onclick = function () {
      if (mySwipe) {
        mySwipe.kill();
        mySwipe = null;
      }
    }
    wrapper.onmouseenter = function () {
      clearTimeout(myFadeTimeout);
      fadeIn(itemsElem, 200);
    };
    wrapper.onmouseleave = function () {
      myFadeTimeout = setTimeout(function () {
        fadeOut(itemsElem, 200);
      }, 2500);
    }
    wrapper.ontouchstart = function() {
      fadeIn(itemsElem, 200);
    }
    wrapper.append(clonedElem);
    swipeWrapElem.append(wrapper);

    elem.addEventListener('click', async function (e) {
      MicroModal.show('modal');
      if (mySwipe) {
        mySwipe.kill();
        mySwipe = null;
      }

      var imgSrc = e.target.getAttribute('data-src') || e.target.getAttribute('src');
      var img = await imageLoad(imgSrc);
      clonedElem.style.width = img.width + 'px';
      clonedElem.style.height = img.height + 'px';
      
      
      mySwipe = new Swipe(mySwipeElem, {
        startSlide: idx,
        draggable: true,
        autoRestart: false,
        continuous: false,
        disableScroll: true,
        stopPropagation: true,
        callback: async function (index, element) {
          
          var imgElem = element.querySelector('img');
          var imgSrc = imgElem.getAttribute('data-src') || imgElem.getAttribute('src');
          var img = await imageLoad(imgSrc);
          imgElem.style.width = img.width + 'px';
          imgElem.style.height = img.height + 'px';

          
          if (captionElem && imgElem) {
            var caption = null;
            if (imgElem.getAttribute('data-caption')) {
              caption = imgElem.getAttribute('data-caption');
            } else if (imgElem.getAttribute('title')) {
              caption = imgElem.getAttribute('title');
            } else if (imgElem.getAttribute('alt')) {
              caption = imgElem.getAttribute('alt');
            } else {
              caption = imgElem.getAttribute('src');
            }

            captionElem.querySelector('.modal__caption--text').innerText = caption;
            pagingElem.innerText = (index + 1) + ' / ' + imgTotalNum;

            clearTimeout(myFadeTimeout);
            fadeIn(itemsElem, 200);
          }
        },
      });

      fadeIn(itemsElem);

      
      if (captionElem) {
        var caption = null;
        if (e.target.getAttribute('data-caption')) {
          caption = e.target.getAttribute('data-caption');
        } else if (e.target.getAttribute('title')) {
          caption = e.target.getAttribute('title');
        } else if (e.target.getAttribute('alt')) {
          caption = e.target.getAttribute('alt');
        } else {
          caption = e.target.getAttribute('src');
        }

        captionElem.querySelector('.modal__caption--text').innerText = caption;
        pagingElem.innerText = (idx + 1) + ' / ' + imgTotalNum;
      }

      if (normalElem && fullElem) {
        normalElem.style.zIndex = -1;
        normalElem.style.opacity = 0;
        fullElem.style.zIndex = 25;
        fullElem.style.opacity = 1;
      }
    });

    window.addEventListener('keydown', keydownFunction);
  });

  arrowLeftElem ?
    arrowLeftElem.addEventListener('click', function (e) {
      if (mySwipe) {
        mySwipe.prev();
      }
    }) : null;
  arrowRightElem ?
    arrowRightElem.addEventListener('click', function (e) {
      if (mySwipe) {
        mySwipe.next();
      }
    }) : null;

  closeElem ?
    closeElem.addEventListener('click', function () {
      if (mySwipe) {
        mySwipe.kill();
        mySwipe = null;
      }
      closeFullscreen();
      MicroModal.close('modal');
    }) : null;

  fullElem ?
    fullElem.addEventListener('click', function (e) {
      openFullscreen();
      if (normalElem) {
        normalElem.style.zIndex = 25;
        normalElem.style.opacity = 1;
        fullElem.style.zIndex = -1;
        fullElem.style.opacity = 0;
      }
    }) : null;

  normalElem ?
    normalElem.addEventListener('click', function (e) {
      closeFullscreen();
      if (fullElem) {
        fullElem.style.zIndex = 25;
        fullElem.style.opacity = 1;
        normalElem.style.zIndex = -1;
        normalElem.style.opacity = 0;
      }
    }) : null;
  
});
</script>

    <div class="hide">
      

<div class="search">
  <span class="icon">
    <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" fill="currentColor" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0V0z"/><path d="M15.5 14h-.79l-.28-.27c1.2-1.4 1.82-3.31 1.48-5.34-.47-2.78-2.79-5-5.59-5.34-4.23-.52-7.79 3.04-7.27 7.27.34 2.8 2.56 5.12 5.34 5.59 2.03.34 3.94-.28 5.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/></svg>
  </span>
  <input id="search" aria-label="Site Search" class="input" type="text" placeholder="Search" autocomplete="off">
  <div id="search-results" class="dropdown">
    <div id="search-menu" class="dropdown-menu" role="menu">
    </div>
  </div>
</div>


    </div>
  </div>
</main>


<aside class="single__side main-side">
  


<section class="sidebar hide">
  <script>document.querySelector('.sidebar').classList.remove('hide')</script>
  <div class="toc__flexbox" data-position="fixed">
    <h6 class="toc__title" data-ani="true">What&#39;s on this Page</h6>
    
      <label class="switch" data-ani="true">
        <input id="toggle-toc" aria-label="Toggle TOC" type="checkbox" checked>
        <span class="slider round"></span>
      </label>
    
  </div>
  <div class="toc " data-dir="ltr" data-folding="true" data-ani="true">
    <nav id="TableOfContents">
  <ul>
    <li><a href="#begin">Begin</a></li>
    <li><a href="#libpcap常用接口">libpcap常用接口</a></li>
    <li><a href="#抓包方式">抓包方式</a>
      <ul>
        <li><a href="#socket--recvfrom">socket + recvfrom</a></li>
        <li><a href="#tcpdump">Tcpdump</a></li>
        <li><a href="#例程-pcap_loop">例程-pcap_loop</a></li>
      </ul>
    </li>
    <li><a href="#libpcap结构体">libpcap结构体</a></li>
    <li><a href="#pcap_open_live">pcap_open_live</a>
      <ul>
        <li><a href="#pcap_create">pcap_create</a></li>
        <li><a href="#pcap_activate">pcap_activate</a>
          <ul>
            <li><a href="#activate_pf_packet">activate_pf_packet</a></li>
            <li><a href="#setup_mmapped">setup_mmapped</a></li>
            <li><a href="#pcap_read_linux_mmap_v3">pcap_read_linux_mmap_v3</a></li>
          </ul>
        </li>
      </ul>
    </li>
    <li><a href="#pcap_compilepcap_setfilter">pcap_compile&amp;&amp;pcap_setfilter</a></li>
    <li><a href="#pcap_loop">pcap_loop</a></li>
    <li><a href="#kernelnet结构体">kernel/net结构体</a></li>
    <li><a href="#kernelnet-源码">kernel/net 源码</a>
      <ul>
        <li><a href="#netpacketaf_packetcpacket_init">net/packet/af_packet.c/packet_init</a></li>
        <li><a href="#netsocketc">net/socket.c</a></li>
        <li><a href="#netpacketaf_packetcpacket_create">net/packet/af_packet.c/packet_create</a></li>
        <li><a href="#netpacketaf_packetcpacket_rcv">net/packet/af_packet.c/packet_rcv</a></li>
        <li><a href="#netpacketaf_packetcpacket_recvmsg">net/packet/af_packet.c/packet_recvmsg</a></li>
        <li><a href="#recvfrom-cap">recvfrom cap</a></li>
      </ul>
    </li>
    <li><a href="#to-do">To do</a></li>
    <li><a href="#changelog">ChangeLog</a></li>
    <li><a href="#reference">Reference</a></li>
  </ul>
</nav>
  </div>
</section>



</aside>

<script>
  
  
  

  var enableToc = JSON.parse("true");
  var toc = JSON.parse("null");
  var tocPosition = JSON.parse("\"inner\"");
  
  var singleMainElem = document.querySelector('.single__main');
  var singleSideElem = document.querySelector('.single__side');

  enquire.register("screen and (max-width: 769px)", {
    match: function () {
      if ((enableToc || toc) && tocPosition !== "outer") {
        if (singleMainElem && singleSideElem) {
          singleMainElem.classList.remove('main-main');
          singleMainElem.classList.add('main');
          singleSideElem.classList.remove('main-side');
          singleSideElem.classList.add('hide');
        }
      } else if (tocPosition === "outer") {
        if (singleMainElem && !singleMainElem.classList.contains('main-main')) {
          singleMainElem.classList.remove('main-main');
          singleMainElem.classList.add('main');
        }
        if (singleSideElem && !singleSideElem.classList.contains('hide')) {
          singleSideElem.classList.add('hide');
        }
      }
    },
    unmatch: function () {
      if ((enableToc || toc) && tocPosition !== "outer") {
        singleMainElem.classList.remove('main');
        singleMainElem.classList.add('main-main');
        singleSideElem.classList.remove('hide');
        singleSideElem.classList.add('main-side');
      } else if (tocPosition === "outer") {
        if (singleMainElem && !singleMainElem.classList.contains('main-main')) {
          singleMainElem.classList.remove('main-main');
          singleMainElem.classList.add('main');
        }
        if (singleSideElem && !singleSideElem.classList.contains('hide')) {
          singleSideElem.classList.add('hide');
        }
      }

      var navCollapseBtn = document.querySelector('.navbar__burger');
      var navCollapse = document.getElementsByClassName('navbarm__collapse')[0];
      if (navCollapse) {
        navCollapse.setAttribute('data-open', false);
        navCollapse.style.maxHeight = 0;
        navCollapseBtn.classList.remove('is-active');
      }
      document.getElementsByClassName('navbar__menu')[0].classList.remove('is-active');
      document.getElementsByClassName('mobile-search')[0].classList.add('hide');
    },
    setup: function () { },
    deferSetup: true,
    destroy: function () { },
  });
</script>





<script defer src="/js/helper/getParents.min.js"></script>

<script defer src="/js/helper/closest.min.js"></script>

<script defer src="/js/helper/prev.min.js"></script>

<script defer src="/js/helper/prop.min.js"></script>

<script defer src="/js/helper/fadeinout.min.js"></script>

<script defer src="/js/helper/throttle.min.js"></script>






































  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.css" integrity="sha256-V8SV2MO1FUb63Bwht5Wx9x6PVHNa02gv8BgH/uH3ung=" crossorigin="anonymous">
  <script defer src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.js" integrity="sha256-F/Xda58SPdcUCr&#43;xhSGz9MA2zQBPb0ASEYKohl8UCHc=" crossorigin="anonymous"></script>
  <script defer src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/contrib/auto-render.min.js" integrity="sha256-90d2pnfw0r4K8CZAWPko4rpFXQsZvJhTBGYNkipDprI=" crossorigin="anonymous"></script>














<script>
  'use strict';

  window.onload = function() {
    var navbar = document.querySelector('.navbar');
    var singleContentsElem = document.querySelector('.single__contents');

    
    
    
    var enableBusuanzi = JSON.parse("true");
    var busuanziPagePV = JSON.parse("true");
    
    if (enableBusuanzi && busuanziPagePV) {
      var pagePvElem = document.querySelector('#busuanzi_value_page_pv');
      pagePvElem.textContent = pagePvElem.textContent.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
    }    
    



    
    
    
    
    
    
    var enableToc = JSON.parse("true");
    var toc = JSON.parse("null");
    var hideToc = JSON.parse("false");
    var tocFlexbox = document.querySelector('.toc__flexbox');
    var tocFlexboxOuter = document.querySelector('.toc__flexbox--outer');
    var tocFolding = JSON.parse("true");
    
    if ((enableToc || toc) && document.querySelector('.toc')) {
      var tableOfContentsElem = document.querySelector('.toc').querySelector('#TableOfContents');

      tableOfContentsElem.onmouseenter = function() {
        if (navbar.classList.contains('scrolling')) {
          navbar.classList.remove('scrolling');
        }
      }

      tableOfContentsElem.onmouseleave = function() {
        if (!navbar.classList.contains('scrolling')) {
          navbar.classList.add('scrolling');
        }
      }

      if (false === tocFolding) {

      } else {
        tableOfContentsElem.querySelectorAll('ul') ?
          tableOfContentsElem.querySelectorAll('ul').forEach(function (rootUl) {
            rootUl.querySelectorAll('li').forEach(function (liElem) {
              liElem.querySelectorAll('ul').forEach(function (ulElem) {
                ulElem.style.display = 'none';
              });
            });
          }) : null;
      }

      if (tableOfContentsElem) {
        if (tableOfContentsElem.querySelectorAll('a').length > 0) {
          tableOfContentsElem.querySelectorAll('a').forEach(function (elem) {
            elem.addEventListener('click', function () {
              var id = elem.getAttribute('id');

              if (!navbar.classList.contains('scrolling')) {
                navbar.classList.remove('navbar--show');
                navbar.classList.remove('navbar--hide');
                navbar.classList.add('navbar--hide');
              }
              
              document.querySelector('.toc').querySelectorAll('a').forEach(function (elem) {
                elem.classList.remove('active');
              });
              elem.classList.add('active');

              var curElem = tableOfContentsElem.querySelector('[href="#' + id + '"]');
              if (curElem && curElem.nextElementSibling) {
                curElem.nextElementSibling.style.display = 'block';
              }
              if (curElem) {
                getParents(curElem, 'ul') ?
                  getParents(curElem, 'ul').forEach(function (elem) {
                    elem.style.display = 'block';
                  }) : null;
              }
            });
          });
        } else {
          if (tocFlexbox) {
            tocFlexbox.setAttribute('data-position', '');
            if (!tocFlexbox.classList.contains('hide')) {
              tocFlexbox.classList.add('hide');
            }
          }
          if (tocFlexboxOuter) {
            tocFlexboxOuter.setAttribute('data-position', '');
            if (!tocFlexboxOuter.classList.contains('hide')) {
              tocFlexboxOuter.classList.add('hide');
            }
          }
        }
      }

      
      var toggleTocElem = document.getElementById("toggle-toc");
      var visibleTocElem = document.getElementById('visible-toc');
      var tocElem = document.querySelector('.toc');
      var mainElem = document.querySelector('main');
      var sideElem = document.querySelector('side');
      var tocFlexboxElem = document.querySelector('.toc__flexbox');

      toggleTocElem ? 
      toggleTocElem.addEventListener('change', function(e) {
        if (e.target.checked) {
          if (tocElem) {
            fadeIn(tocElem, 200);
          }
          if (tocFlexboxElem) {
            tocFlexboxElem.setAttribute('data-position', 'fixed');
          }

          if (mainElem) {
            mainElem.classList.remove('main-main');
            mainElem.classList.remove('main');
            mainElem.classList.add('main-main');
          }
          if (sideElem) {
            sideElem.classList.remove('main-side');
          }
        } else {
          if (tocElem) {
            fadeOut(tocElem, 200);
          }
          if (tocFlexboxElem) {
            tocFlexboxElem.setAttribute('data-position', 'absolute');
          }

          if (mainElem) {
            mainElem.classList.remove('main-main');
            mainElem.classList.remove('main');
            mainElem.classList.add('main');
          }
          if (sideElem) {
            sideElem.classList.remove('main-side');
          }
        }
      }) : null;

      visibleTocElem ?
      visibleTocElem.addEventListener('change', function(e) {
        if (e.target.checked) {
          if (tocElem) {
            fadeIn(tocElem, 200);
          }
        } else {
          if (tocElem) {
            fadeOut(tocElem, 200);
          }
        }
      }) : null;
    }
    
    
    
    
    
    var topOffset = 120;
    var botOffset = 70;
    var handleWindowResize = function () {
      if (tocElem) {
        tocElem.style.maxHeight = (window.innerHeight - topOffset - botOffset) + 'px';
      }
    }
    var throttledWindowResize = throttle(handleWindowResize, 300);
    throttledWindowResize()

    
    window.addEventListener('resize', throttledWindowResize);
    



    
    var text, clip = new ClipboardJS('.anchor');
    var headers = singleContentsElem.querySelectorAll("h1, h2, h3, h4");

    
    var languagedir = JSON.parse("\"ltr\"");

    headers ? 
    headers.forEach(function (elem) {
      var size = parseInt(elem.tagName.substr(1), 10) * 2;
      var url = encodeURI(document.location.origin + document.location.pathname);
      var link = url + "#" + elem.getAttribute('id');
      var newElemOuter = document.createElement('span');
      newElemOuter.classList.add('anchor');
      newElemOuter.classList.add('hide');
      newElemOuter.setAttribute('data-clipboard-text', decodeURI(link));
      newElemOuter.style.position = 'relative';

      var newElemInner = document.createElement('span');
      newElemInner.style.position = 'absolute';
      newElemInner.style.top = '50%';
      newElemInner.style.left = '0.75rem';
      newElemInner.style.transform = 'translateY(-50%)';
      newElemInner.innerHTML = `
<svg fill="currentColor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="${32 - size}px" height="${32 - size}px"><path d="M 5.5625 0 C 4.136719 0 2.707031 0.542969 1.625 1.625 C -0.539063 3.789063 -0.539063 7.335938 1.625 9.5 L 5.28125 13.15625 C 5.667969 13.554688 6.304688 13.558594 6.703125 13.171875 C 7.101563 12.785156 7.105469 12.148438 6.71875 11.75 L 3.03125 8.0625 C 1.632813 6.664063 1.632813 4.429688 3.03125 3.03125 C 4.429688 1.632813 6.664063 1.632813 8.0625 3.03125 L 12.96875 7.9375 C 14.367188 9.335938 14.367188 11.570313 12.96875 12.96875 C 12.804688 13.132813 12.621094 13.25 12.4375 13.375 C 11.980469 13.6875 11.859375 14.308594 12.171875 14.765625 C 12.484375 15.222656 13.105469 15.34375 13.5625 15.03125 C 13.847656 14.835938 14.125 14.625 14.375 14.375 C 16.539063 12.210938 16.539063 8.664063 14.375 6.5 L 9.5 1.625 C 8.417969 0.542969 6.988281 0 5.5625 0 Z M 10.78125 8.875 C 10.738281 8.882813 10.695313 8.894531 10.65625 8.90625 C 10.507813 8.9375 10.371094 9 10.25 9.09375 C 10.039063 9.253906 9.820313 9.429688 9.625 9.625 C 7.460938 11.789063 7.460938 15.335938 9.625 17.5 L 14.5 22.375 C 16.664063 24.539063 20.210938 24.539063 22.375 22.375 C 24.539063 20.210938 24.539063 16.664063 22.375 14.5 L 18.71875 10.875 C 18.476563 10.578125 18.089844 10.441406 17.714844 10.527344 C 17.34375 10.613281 17.050781 10.90625 16.964844 11.277344 C 16.878906 11.652344 17.015625 12.039063 17.3125 12.28125 L 20.96875 15.9375 C 22.367188 17.335938 22.367188 19.570313 20.96875 20.96875 C 19.570313 22.367188 17.335938 22.367188 15.9375 20.96875 L 11.03125 16.0625 C 9.632813 14.664063 9.632813 12.429688 11.03125 11.03125 C 11.152344 10.90625 11.300781 10.820313 11.4375 10.71875 C 11.839844 10.472656 12.015625 9.976563 11.855469 9.53125 C 11.699219 9.085938 11.25 8.8125 10.78125 8.875 Z"/></svg>`;

      if (languagedir === "rtl") {
        newElemInner.style.left = '-2rem';
      } else {
        newElemInner.style.right = '-2rem';
      }

      newElemOuter.append(newElemInner);
      elem.append(newElemOuter);

      elem.addEventListener('mouseenter', function() {
        this.querySelector('.anchor').classList.remove('hide');
      });
      elem.addEventListener('mouseleave', function () {
        this.querySelector('.anchor').classList.add('hide');
      });
    }) : null;

    document.querySelectorAll('.anchor').forEach(function(elem) {
      elem.addEventListener('mouseleave', function() {
        elem.setAttribute('aria-label', null);
        elem.classList.remove('tooltipped');
        elem.classList.remove('tooltipped-s');
        elem.classList.remove('tooltipped-w');
      });
    });

    clip.on('success', function (e) {
      e.clearSelection();
      e.trigger.setAttribute('aria-label', 'Link copied to clipboard!');
      e.trigger.classList.add('tooltipped');
      e.trigger.classList.add('tooltipped-s');
    });
    // =================================================================



    
    
    var lib = JSON.parse("[\"katex\"]");

    if (lib && lib.includes('mermaid')) {
      
      var themeVariant = localStorage.getItem('theme') || JSON.parse("\"dark\"");

      if (themeVariant === "dark" || themeVariant === "hacker") {
        mermaid.initialize({ theme: 'dark' });
      } else {
        mermaid.initialize({ theme: 'default' });
      }
      
      var mermaids = [];
      [].push.apply(mermaids, document.getElementsByClassName('language-mermaid'));
      mermaids.forEach(function(elem) {
        var elemParentNode = elem.parentNode;

        if (elemParentNode !== document.body) {
          elemParentNode.parentNode.insertBefore(elem, elemParentNode);
          elemParentNode.parentNode.removeChild(elemParentNode);
        }

        var newElemWrapper = document.createElement('div');
        newElemWrapper.classList.add('mermaid');
        newElemWrapper.style.padding = '34px 4px 6px';
        newElemWrapper.innerHTML = elem.innerHTML;
        elem.replaceWith(newElemWrapper);
      });
    }
    

    

    
    if (lib && lib.includes('katex')) {
      var mathElements = document.getElementsByClassName('math');
      var options = {
        delimiters: [
          { left: "$$", right: "$$", display: true },
          { left: "\\[", right: "\\]", display: true },
          { left: "$", right: "$", display: false },
          { left: "\\(", right: "\\)", display: false }
        ],
      };

      renderMathInElement(document.querySelector('.single__contents'), options);
    }
    



    
    if (lib && lib.includes('flowchartjs')) {
      
      var options = JSON.parse("{\"arrow-end\":\"block\",\"element-color\":\"black\",\"fill\":\"white\",\"flowstate\":{\"approved\":{\"fill\":\"#58C4A3\",\"font-size\":12,\"no-text\":\"n/a\",\"yes-text\":\"APPROVED\"},\"current\":{\"fill\":\"yellow\",\"font-color\":\"red\",\"font-weight\":\"bold\"},\"future\":{\"fill\":\"#FFFF99\"},\"invalid\":{\"fill\":\"#444444\"},\"past\":{\"fill\":\"#CCCCCC\",\"font-size\":12},\"rejected\":{\"fill\":\"#C45879\",\"font-size\":12,\"no-text\":\"REJECTED\",\"yes-text\":\"n/a\"},\"request\":{\"fill\":\"blue\"}},\"font-color\":\"black\",\"font-size\":14,\"line-color\":\"black\",\"line-length\":50,\"line-width\":3,\"no-text\":\"no\",\"scale\":1,\"symbols\":{\"end\":{\"class\":\"end-element\"},\"start\":{\"element-color\":\"green\",\"fill\":\"yellow\",\"font-color\":\"red\"}},\"text-margin\":10,\"x\":0,\"y\":0,\"yes-text\":\"yes\"}");
      var jsonContent = null;

      var flowchartPrefix = "language-flowchart";
      var index = 0;
      Array.prototype.forEach.call(document.querySelectorAll("[class^=" + flowchartPrefix + "]"), function(x){
          x.style.display = 'none'
          x.parentNode.style.backgroundColor = "transparent"
          jsonContent = x.innerText;

          var node0 = document.createElement('div');
          node0.id = 'flowchart' + index;
          x.parentNode.insertBefore(node0, x);

          var diagram = flowchart.parse(jsonContent);
          diagram.drawSVG("flowchart"+index, options);

          index +=1;
      });      
    }
    

    

    
    document.querySelectorAll("mjx-container").forEach(function (x) {
      x.parentElement.classList += 'has-jax'
    });
    



    
    if (lib && lib.includes('msc')) {
      
      var options = JSON.parse("{\"theme\":\"hand\"}");
      var jsonContent = null;

      var index = 0;
      var chartPrefix = "language-msc";
      Array.prototype.forEach.call(document.querySelectorAll("[class^=" + chartPrefix + "]"), function (x) {
        x.style.display = 'none'
        x.parentNode.style.backgroundColor = "transparent"
        jsonContent = x.innerText;
        var node0 = document.createElement('div');
        node0.id = 'msc' + index;
        x.parentNode.insertBefore(node0, x);
        var diagram = Diagram.parse(jsonContent);
        diagram.drawSVG("msc" + index, options);
        index += 1;
      });
    }
    



    
    if (lib && lib.includes('chart')) {
      var borderColor = "#666";
      var bgColor = "#ddd";
      var borderWidth = 2;

      Chart.defaults.global.elements.rectangle.borderWidth = borderWidth;
      Chart.defaults.global.elements.rectangle.borderColor = borderColor;
      Chart.defaults.global.elements.rectangle.backgroundColor = bgColor;

      Chart.defaults.global.elements.line.borderWidth = borderWidth;
      Chart.defaults.global.elements.line.borderColor = borderColor;
      Chart.defaults.global.elements.line.backgroundColor = bgColor;

      Chart.defaults.global.elements.point.borderWidth = borderWidth;
      Chart.defaults.global.elements.point.borderColor = borderColor;
      Chart.defaults.global.elements.point.backgroundColor = bgColor;

      var chartPrefix = "language-chart";
      var index = 0;
      var jsonContent = null;

      Array.prototype.forEach.call(document.querySelectorAll("[class^=" + chartPrefix + "]"), function (x) {
        x.style.display = 'none'
        x.parentNode.style.backgroundColor = "transparent"
        jsonContent = x.innerText;
        var node0 = document.createElement('canvas');
        var source = null;
        node0.height = 200;
        node0.style.height = 200;
        node0.id = 'myChart' + index;
        source = JSON.parse(jsonContent);
        x.parentNode.insertBefore(node0, x);
        var ctx = document.getElementById('myChart' + index).getContext('2d');
        var myChart = new Chart(ctx, source);
        index += 1;
      });            
    }
    



    
    if (lib && lib.includes('wavedrom')) {
      var wavePrefix = "language-wave";
      var index = 0;
      var jsonContent = null;
      
      Array.prototype.forEach.call(document.querySelectorAll("[class^=" + wavePrefix + "]"), function (x) {
        x.style.display = 'none'
        x.parentNode.style.backgroundColor = "transparent"
        jsonContent = x.innerText;
        var node0 = document.createElement('div');
        var source = null;
        node0.id = 'WaveDrom_Display_' + index;
        source = JSON.parse(jsonContent);
        x.parentNode.insertBefore(node0, x);
        WaveDrom.RenderWaveForm(index, source, "WaveDrom_Display_");
        index += 1;
      });
    }
    



    
    if (lib && lib.includes('viz')) {
      var vizPrefix = "language-viz-";
      Array.prototype.forEach.call(document.querySelectorAll("[class^=" + vizPrefix + "]"), function (x) {
        x.style.display = 'none'
        x.parentNode.style.backgroundColor = "transparent"
        var engine;
        x.getAttribute("class").split(" ").forEach(function (cls) {
          if (cls.startsWith(vizPrefix)) {
            engine = cls.substr(vizPrefix.length);
          }
        });
        var viz = new Viz();
        viz.renderSVGElement(x.innerText, { engine: engine })
          .then(function (element) {
            element.style.width = "100%";
            x.parentNode.insertBefore(element, x);
          })
      });
    }
    
    
  }
</script>


            
            <footer class="footer">
    
<div class="dropdown">
  <button class="dropdown-trigger" aria-label="Select Language Button">
    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0V0z"/><path fill="currentColor" d="M12.65 15.67c.14-.36.05-.77-.23-1.05l-2.09-2.06.03-.03c1.74-1.94 2.98-4.17 3.71-6.53h1.94c.54 0 .99-.45.99-.99v-.02c0-.54-.45-.99-.99-.99H10V3c0-.55-.45-1-1-1s-1 .45-1 1v1H1.99c-.54 0-.99.45-.99.99 0 .55.45.99.99.99h10.18C11.5 7.92 10.44 9.75 9 11.35c-.81-.89-1.49-1.86-2.06-2.88-.16-.29-.45-.47-.78-.47-.69 0-1.13.75-.79 1.35.63 1.13 1.4 2.21 2.3 3.21L3.3 16.87c-.4.39-.4 1.03 0 1.42.39.39 1.02.39 1.42 0L9 14l2.02 2.02c.51.51 1.38.32 1.63-.35zM17.5 10c-.6 0-1.14.37-1.35.94l-3.67 9.8c-.24.61.22 1.26.87 1.26.39 0 .74-.24.88-.61l.89-2.39h4.75l.9 2.39c.14.36.49.61.88.61.65 0 1.11-.65.88-1.26l-3.67-9.8c-.22-.57-.76-.94-1.36-.94zm-1.62 7l1.62-4.33L19.12 17h-3.24z"/></svg>
  </button>
  <div class="dropdown-content">
    
    
    
  </div>
</div>

    
    
<div id="gtt">
  <div class="gtt">
    <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24"><path fill="currentColor" d="M8.12 14.71L12 10.83l3.88 3.88c.39.39 1.02.39 1.41 0 .39-.39.39-1.02 0-1.41L12.7 8.71c-.39-.39-1.02-.39-1.41 0L6.7 13.3c-.39.39-.39 1.02 0 1.41.39.38 1.03.39 1.42 0z"/></svg>
  </div>
</div>

    <hr />

    <div class="basicflex flexwrap">
        
            
        
            
        
    </div>

    <div class="footer__poweredby">
        
  <div class="busuanzi">
    
    
      <div class="busuanzi__item">
        <span class="busuanzi__item--label">
          Total visitors
        </span>
        <span id="busuanzi_value_site_uv" class="busuanzi__item--number">...</span>
      </div>
    

    
      <div class="busuanzi__item">
        <span class="busuanzi__item--label">
          Total views
        </span>
        <span id="busuanzi_value_site_pv" class="busuanzi__item--number">...</span>
      </div>
    

  </div>

                
            <p class="caption">
                
                    ©2023, All Rights Reserved
                
            </p>
        

        
        
    </div> 
</footer>
        </div>
        





<div class="wrapper__right hide" data-pad="true" dir="ltr">
  <script>document.querySelector('.wrapper__right').classList.remove('hide')</script>
  
</div>

    </div>
</body>

</html>